我可以得到实体框架,而不是使用接口的具体类(用于Web服务序列化) [英] Can I get the entity framework to use concrete classes instead of interfaces (for web service serialisation)
问题描述
我正在学习有关Web服务,我现在用的书是从SQL Server使用实体框架(我不太了解太)提取数据。
I am learning about web services and the book I am using is pulling data from SQL server using the entity framework (which I know little about too).
不幸的是由实体框架创建的类包含的东西,如:
Unfortunately the classes created by the entity framework contain things like:
public Conference()
{
this.Sessions = new HashSet<Session>();
}
public virtual ICollection<Session> Sessions { get; set; }
这导致一个问题,因为接口没有serialisable:
Which causes a problem because an interface is not serialisable:
无法序列类型的成员X 了System.Collections.Generic.ICollection ...因为它是一个接口
Cannot serialize member X of type System.Collections.Generic.ICollection ... because it is an interface.
现在我可以(做)修改生成的类使用具体的类,但如果我以往任何时候都需要重新生成实体那么这种改变将被撤消。理想情况下,我可以告诉实体框架来产生这样的事情(甚至更好,有具体类型的控制,所以我可以告诉实体框架使用一个列表,如果我愿意的话):
Now I could (and did) modify the generated classes to use concrete classes but if I ever need to regenerate the entities then that change will be undone. Ideally I could tell the entity framework to generate something like this (or even better, have control of the concrete type so I could tell the entity framework to use a List if I want to):
public Conference()
{
this.Sessions = new HashSet<Session>();
}
public virtual HashSet<Session> Sessions { get; set; }
这可能吗?如果是这样,怎么样?
Is it possible? If so, how?
推荐答案
我用<一个href="http://www.dotnet-tricks.com/Tutorial/entityframework/L0EV220314-Using-T4-templates-in-Entity-framework.html"相对=nofollow> T4模板。
在模板中,我改变了的ICollection
到列表
,并添加 [Serializable接口]
来实体类型和复杂类型。
In the template, I changed ICollection
to List
, and added [Serializable]
to entity types and complex types.
我也不得不禁用代理类型的产生:
I also had to disable proxy type generation:
((IObjectContextAdapter)entities).ObjectContext.ContextOptions.ProxyCreationEnabled = false;
这篇关于我可以得到实体框架,而不是使用接口的具体类(用于Web服务序列化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!