Entity framework 模板修改后的InvalidOperationException(集合已设置为EntityCollection)所有属性都是虚拟的
DbContext实体的默认tt在实体的构造函数中添加集合项目的初始化代码。每个集合都分配了空哈希集Entity framework 模板修改后的InvalidOperationException(集合已设置为EntityCollection)所有属性都是虚拟的,entity-framework,entity-framework-4.1,entity-framework-5,t4,dbcontext,Entity Framework,Entity Framework 4.1,Entity Framework 5,T4,Dbcontext,DbContext实体的默认tt在实体的构造函数中添加集合项目的初始化代码。每个集合都分配了空哈希集 对于标量实体属性,tt有以下代码: public string Property(EdmProperty edmProperty) { return string.Format( CultureInfo.InvariantCulture, "{0} {1} {2} {{ {3}get; {4}set; }}", Accessibility.
对于标量实体属性,tt有以下代码:
public string Property(EdmProperty edmProperty)
{
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
Accessibility.ForProperty(edmProperty),
_typeMapper.GetTypeName(edmProperty.TypeUsage),
_code.Escape(edmProperty),
_code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
_code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}
如果我将其更改为:
public string Property(EdmProperty edmProperty)
{
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
AccessibilityAndVirtual(Accessibility.ForProperty(edmProperty)),
_typeMapper.GetTypeName(edmProperty.TypeUsage),
_code.Escape(edmProperty),
_code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
_code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}
添加AccessibilityAndVirtual()EF开始抛出InvalidOperationException,表示集合已设置为EntityCollection。为什么会发生这种情况 更新:
从PK属性中删除虚拟将删除异常 只有当PK属性是虚拟的时才会抛出异常,所以我稍微更改了
属性的代码
public string Property(EdmProperty edmProperty, MetadataTools ef)
{
var acessability = Accessibility.ForProperty(edmProperty);
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
ef.IsKey(edmProperty) ? acessability : AccessibilityAndVirtual(acessability),
_typeMapper.GetTypeName(edmProperty.TypeUsage),
_code.Escape(edmProperty),
_code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
_code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}
我知道这是一个老问题,但我也有同样的问题,@Pavel的答案对我来说并不适用
事实证明,当您将所有属性设置为虚拟时,您就实现了更改跟踪代理。在这种情况下,更改跟踪代理将覆盖任何集合导航属性,并使用其自己的集合类型(EntityCollection)。这就是为什么必须取消类构造函数中导航属性的任何初始化。(在每个部分类中删除NavigationProperty=new HashSet())此代码对我来说很好-所有属性都添加了virtual
修饰符。没有例外。@lazyberezovsky和您的实体有集合类型导航属性?是的,它有ICollection
,在构造函数中初始化为new HashSet()
,这很奇怪。。。代理问题…但不知道为什么。昨天,另一个DB也出现了同样的问题。我不得不将此代码用于Format()调用的第三个参数:_ef.IsKey(edmProperty)?Accessibility.ForProperty(edmProperty):Accessibility和dvirtual(Accessibility.ForProperty(edmProperty)),