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

h.a*_*lex 3 c# virtual entity-framework properties

我有一个db第一个edmx模型.它生成的部分类具有非虚拟简单属性.例如

//------------------------------------------------------------------------------
// <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.
    }
Run Code Online (Sandbox Code Playgroud)

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

h.a*_*lex 8

这里一个简单的解决方案.

展开模型edmx并编辑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)));
}
Run Code Online (Sandbox Code Playgroud)

一个简单的编辑就足够了:

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)));
}
Run Code Online (Sandbox Code Playgroud)

就是这样,供后代参考.