C# 实体框架6代码首先不创建所有列
我首先使用EF6和代码创建一个简单的表。除了C# 实体框架6代码首先不创建所有列,c#,entity-framework,entity-framework-6,C#,Entity Framework,Entity Framework 6,我首先使用EF6和代码创建一个简单的表。除了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 N
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
。为什么会这样?Iguess这是因为该字段是只读的,因为它只有一个getter:
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; }
}
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; }
}
正如前面所指出的,它是一个只读属性,没有setter的属性不会被实体框架映射。通过这样做,实体框架可以避免映射不应该映射的属性,例如计算属性 一个可能的选项是使用
private
设置器进行设置。这将使实体框架能够将其视为读写属性,并对其进行映射
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文档链接中找到:,该链接可以让您了解后台正在发生的事情
EntityFrameworkCore还提供了一种简单的方法,可以使用其他替代方法,例如
另外,还使用.NET Framework和Entity Framework 6测试了一个简单的控制台应用程序,其中一个
private
setter正在映射属性。不幸的是,这只适用于EF Core。作者使用EF6。@AlexanderPetrov,谢谢你的评论,我监督了EF6的提及,并默认为实体框架核心。我还编辑了答案,并给出了更清晰的解释。