实体框架和WCF(返回实体附加到上下文) [英] Entity Framework and WCF (Returning Entities Attached To Context)

查看:77
本文介绍了实体框架和WCF(返回实体附加到上下文)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WCF服务,在我的一个Repository对象中调用以下方法,以在数据库中创建一个新的销售对象。

  {
using(var ctx = new DBcontext())
{
ctx.Sales.AddObject(sale);
ctx.SaveChanges();
退货;
}
}

调用它的WCF方法看起来像这样

  public Sale SaleNew(Sale sale)
{
return SaleRepository.New(sale);
}

当我从客户端应用程序调用它时,我收到以下错误



底层连接已关闭:连接意外关闭。



如果我一步一步的所有代码似乎运行良好,记录被转入数据库。如果在SaveChanges之后,我将以下行添加到我的存储库方法中。

  ctx.Detach(sale); 

异常发生是因为一旦方法返回,我正在处理上下文以这种方式使用实体上下文,即将其直接处理?我只是这样做,因为它的SOA和几乎无状态,所以我的所有存储库方法创建上下文返回值并处理上下文。任何传入的东西都将被添加到上下文或重新附加。

解决方案

根据建议,我打开了WCF中的跟踪并看了发生了什么。发生了代理异常。在这种情况下,当我使用我自己的POCO对象时,我并不希望使用代理对象,所以我将DatabaseContext中的ContextOptions.ProxyCreationEnabled属性设置为false,现在可以正常工作。


I have a WCF service that calls the following method in one of my Repository objects to create a new sale object in the database

public static Sale New(Sale sale)
{
    using (var ctx = new DBcontext())
    {
        ctx.Sales.AddObject(sale);
        ctx.SaveChanges();
        return sale;
    }
}

The WCF method calling this looks like this

public Sale SaleNew(Sale sale)
{
    return SaleRepository.New(sale);
}

When I call this from a client application I get the following error

"The underlying connection was closed: The connection was closed unexpectedly."

If I step through all the code seems to run fine and the record gets insterted into the database. If I add the following line to my repository method after the SaveChanges it works fine

ctx.Detach(sale);

Is the exception happening because I'm disposing the context as soon as the method returns? Is using the entity context in this way bad practise ie disposing of it straight away? I'm only doing this because its SOA and pretty much stateless so all my repository methods create the context return the value and dispose the context. Anything that is passed in will either get added to the context or re-attached.

解决方案

As advised I turned on tracing in WCF and watched what was happening. There was a proxy exception occurring. In this case as I'm using my own POCO objects I don't really want proxy objects so I set the ContextOptions.ProxyCreationEnabled property in my DatabaseContext to false and it now works fine.

这篇关于实体框架和WCF(返回实体附加到上下文)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆