Code First在运行时生成两个属性相同的名称

时间:2017-03-20 19:22:40

标签: entity-framework ef-code-first

我首先使用EntityFramework代码。让我们说这是我的课程:

public abstract class BlockModel
{
    public int Id { get; set; }
}

public class ModuleBlockModel : BlockModel
{

}

public abstract class BlockModelParameter
{
   public int Id { get; set; }
   public virtual BlockModel BlockModel { get; set; }
}

public class ModuleBlockModelParameter : BlockModelParameter
{
   public new virtual ModuleBlockModel BlockModel { get; set; }
}

和我的DbContext类:

public IDbSet<ModuleBlockModel> BlockModels { get; set; }
public IDbSet<ModuleBlockModelParameter> BlockModelParameters { get; set;}

当我尝试获取物品时,EF会创建另一个属性相同的名称。一个是null而另一个是正确的。

Sample

并尝试将BlockModel值抛出null值。

是否有EF错误?如何正确获取BlockModel属性。

感谢。

1 个答案:

答案 0 :(得分:1)

问题在于,您无法使用属性virtual BlockModel BlockModel“隐藏”属性new virtual ModuleBlockModel BlockModel,因为它在技术上是一种不同类型的签名,即使其中一个是另一个的子类型。

您可以尝试使用泛型来解决这个问题(它们允许动态设置'type'),如下所示:

public abstract class BlockModel
{
    public int Id { get; set; }
}

public class ModuleBlockModel : BlockModel
{

}

public abstract class BlockModelParameter<TBlockModel>
    // Guarantee that TBlockModel is sub-type of BlockModel
    where TBlockModel : BlockModel
{
    public int Id { get; set; }

    // Type of BlockModel will be whatever type is specified for TBlockModel
    public virtual TBlockModel BlockModel { get; set; }
}

// Specify ModuleBlockModel as the generic type argument for BlockModelParameter
// Note: A subtype of a generic class doesn't also have to be generic
public class ModuleBlockModelParameter 
    : BlockModelParameter<ModuleBlockModel>
{
    // Now you can 'hide' the parent's BlockModel property, since the 
    // signatures match - or, better yet, you can omit it entirely, 
    // unless you need a type-specific implementation
    public new virtual ModuleBlockModel BlockModel { get; set; }
}