Entity Framework 6 代码优先不创建所有列

Entity Framework 6 code-first not creating all columns

我正在使用 EF6 和代码创建一个简单的 table。除 CreateDate 列外,所有字段均已创建。这是为什么?

public class InspectionPoint
{
    public DateTime CreateDate { get; }
    public string Detail { get; set; }
    public int Id { get; set; }
    public bool IsActive { get; set; }
    public string Name { get; set; }
    public string Question { get; set; }
    public DateTime UpdateDate { get; set; }
}

正在按预期创建 UpdateDate 字段,但未创建 CreateDate。这是为什么?

猜测是因为那个字段是只读的,因为它只有一个getter:

public class InspectionPoint
{
    // only has "get"ter - therefore it's readonly 
    public DateTime CreateDate { get; }      

    // Every other field has both "get" and "set" and can be set to new values
    public string Detail { get; set; }
    public int Id { get; set; }
    public bool IsActive { get; set; }
    public string Name { get; set; }
    public string Question { get; set; }
    public DateTime UpdateDate { get; set; }
}

正如 @marc_s 已经指出的,它是只读的 属性,没有 setter 的属性不会被 Entity Framework 映射。通过这样做,Entity Framework 避免映射不应映射的属性,例如计算属性。

一个可能的选项是用 private setter 设置它。这将使 Entity Framework 将其视为读写 属性 并将其映射。

public class InspectionPoint
{
    public DateTime CreateDate { get; private set; }
    public string Detail { get; set; }
    public int Id { get; set; }
    public bool IsActive { get; set; }
    public string Name { get; set; }
    public string Question { get; set; }
    public DateTime UpdateDate { get; set; }
}

可以在以下 Microsoft 文档中找到更多信息 link:Entity Framework Core Read-only properties,它可以让您深入了解后台发生的事情。

Entity Framework Core 还提供了一种简单的方法来使用其他替代方法,例如 backing fields.

另外使用 .NET Framework 和 Entity Framework 6 测试了一个简单的控制台应用程序,其中 private setter 映射 属性.