EF 6数据库首先使所有属性在生成的实体类中虚拟化

时间:2015-06-01 13:50:11

标签: c# entity-framework properties virtual

我有一个db first edmx模型。它生成的部分类具有非虚拟简单属性。 E.g。

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

    public partial class Entity
    {
     public int Id {get;set;} //not virtual
     public string SomeOtherProperty {get;set;} //also not virtual
     public virtual ICollection<RelatedEntity> RelatedCollection {get;set;} //but 'navigational' properties are virtual.
    }

如何告诉设计师虚拟所有属性?

1 个答案:

答案 0 :(得分:8)

一个简单的解决方案。

Expand the model edmx and edit the Model.tt

在文件中,找到CodeStringGenerator类,查找此方法:

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; }}",
        //make properties virtual.
        AccessibilityAndVirtual(Accessibility.ForProperty(edmProperty)),
        _typeMapper.GetTypeName(edmProperty.TypeUsage),
        _code.Escape(edmProperty),
        _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
        _code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}

这就是它,供后代参考。