EF 代码首先无法对非复杂空对象进行提交
EF code first unable to do commit on a non-complex null object
我目前首先在 SQL 服务器上使用 EF 代码。
这是我的代码:
public class Article
{
public Article(string title, ValidPeriod published)
{
this.Title = title;
this.Published = published;
}
public int Id { get; set; }
public string Title {get;set;}
public ValidPeriod Published { get; set; }
}
public class ValidPeriod()
{
public DateTime From { get; set; }
public DateTime To { get; set; }
}
我能够创建文章的实例 class,但是当我尝试使用 null ValidPeriod 保留文章时,我得到 "Null value for non-nullable member."。我该如何解决这个问题。如何保留空值 class。我没有将 ValidPeriod 声明为复杂对象。
一种可能的解决方案是首先为 ValidPeriod
实体定义主键 Id
,如下所示:
public int Id { get; set; }
然后向 Article
实体添加显式可为 null 的外键(int?
作为可为 null int
):
public int? ValidPeriodId { get; set; }
最后使用 fluent api:
定义 Article
实体的关系
HasOptional(c => c.Published)
.WithMany()
.HasForeignKey(c => c.ValidPeriodId);
我目前首先在 SQL 服务器上使用 EF 代码。
这是我的代码:
public class Article
{
public Article(string title, ValidPeriod published)
{
this.Title = title;
this.Published = published;
}
public int Id { get; set; }
public string Title {get;set;}
public ValidPeriod Published { get; set; }
}
public class ValidPeriod()
{
public DateTime From { get; set; }
public DateTime To { get; set; }
}
我能够创建文章的实例 class,但是当我尝试使用 null ValidPeriod 保留文章时,我得到 "Null value for non-nullable member."。我该如何解决这个问题。如何保留空值 class。我没有将 ValidPeriod 声明为复杂对象。
一种可能的解决方案是首先为 ValidPeriod
实体定义主键 Id
,如下所示:
public int Id { get; set; }
然后向 Article
实体添加显式可为 null 的外键(int?
作为可为 null int
):
public int? ValidPeriodId { get; set; }
最后使用 fluent api:
定义Article
实体的关系
HasOptional(c => c.Published)
.WithMany()
.HasForeignKey(c => c.ValidPeriodId);