Entity Framework中外键属性设置IsModified报错原因排查
问题:EF Core设置外键属性为修改状态时报错原因分析
执行代码dataContext.Entry(this).Property(property).IsModified = true;时出现如下报错,该问题仅在外键属性上出现,非外键属性无此异常,请问报错原因是什么?
The property 'RankingId' on entity type 'TeamOrganizationSeason' cannot be used for objects of type Nullable1 because it is a property for objects of type Nullable1.
相关代码:
public class TeamOrganizationSeason { public int? RankingId { get; set; } [ForeignKey("RankingId")] public Ranking Ranking { get; set; } public void IsUpdated(TeamOrganizationSeason teamOrganizationSeason, DataContext dataContext) { Update(RankingId, teamOrganizationSeason.RankingId, dataContext, t => t.RankingId); } private void Update(double? current, double? original, DataContext dataContext, Expression<Func<TeamOrganizationSeason, double?>> property) { if (current != original) { var state = dataContext.Entry(this).State; dataContext.TeamOrganizationSeasons.Attach(this); dataContext.Entry(this).Property(property).IsModified = true; }; } }
报错原因
核心问题是类型不匹配:
- 实体类中
RankingId的类型是int?(可空整数),但Update方法的参数current、original定义为double?,属性表达式property的返回类型也要求是double?。 - 当传入
t => t.RankingId(int?类型属性)到期望double?类型的参数时,EF Core解析属性表达式时会出现类型兼容错误,报错信息描述模糊,但本质是类型不匹配导致属性元数据无法正确映射。 - 非外键属性无报错,是因为这些属性的类型刚好和
Update方法的double?参数匹配,而外键RankingId的int?类型触发了不兼容问题。
解决方法
方法1:匹配具体类型
修改Update方法的参数类型,使其与RankingId的int?一致:
private void Update(int? current, int? original, DataContext dataContext, Expression<Func<TeamOrganizationSeason, int?>> property) { if (current != original) { var state = dataContext.Entry(this).State; dataContext.TeamOrganizationSeasons.Attach(this); dataContext.Entry(this).Property(property).IsModified = true; }; }
方法2:泛型兼容多类型
如果需要支持多种数值类型的属性修改,改为泛型方法:
private void Update<T>(T current, T original, DataContext dataContext, Expression<Func<TeamOrganizationSeason, T>> property) where T : struct { if (!EqualityComparer<T>.Default.Equals(current, original)) { var state = dataContext.Entry(this).State; dataContext.TeamOrganizationSeasons.Attach(this); dataContext.Entry(this).Property(property).IsModified = true; }; }
内容的提问来源于stack exchange,提问作者Mike Flynn
相关产品推荐
相关产品推荐

