Entity Framework 从版本 3.1.2 升级到 5.0.3 后核心 Include() 不工作
Entity Framework core Include() is not working after upgrading from version 3.1.2 to 5.0.3
我有一个项目是 运行 .net core 3.1。升级到 .net 5 和 entity framework 核心到 5.0.3 后,包含不再工作。
我有这些类
public class Question
{
[Key]
public Guid Id { get; set; }
public string QuestionCode { get; set; }
[ForeignKey("AnswersId")]
public Answer Answers { get; set; }
}
public class Answer
{
[Key]
public Guid Id { get; set; }
public string Answers { get; set; }
public int Score { get; set; }
}
关系定义如下:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Question>()
.HasOne(q => q.Answers);
}
和这个简单的 LINQ:
return _context.Questions
.Include(q => q.Answers)
.FirstOrDefault(s => s.Id == id);
不过。版本升级后包含不起作用。不工作我的意思是返回值不包括答案。仅返回主实体,子实体中的所有字段均为空。
我不是 100% 确定这是否是问题所在,因为您说它之前工作正常,但可能是您的关系在 OnModelCreating
中配置不正确,因为它缺少调用 WithOne
或 WithMany
是正确的。
来自docs:
After calling this method, you should chain a call to WithMany(String) or WithOne(String) to fully configure the relationship. Calling just this method without the chained call will not produce a valid relationship.
有一个breaking change in EF 5 related to the semantics of a required nagivation property from the principal (Question) to the dependant (Answer),可能是升级库后错误行为的解释。
让我们试一试...尝试像这样配置您的关系:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Question>()
.HasOne(q => q.Answers);
.WithOne()
.IsRequired();
}
我有一个项目是 运行 .net core 3.1。升级到 .net 5 和 entity framework 核心到 5.0.3 后,包含不再工作。
我有这些类
public class Question
{
[Key]
public Guid Id { get; set; }
public string QuestionCode { get; set; }
[ForeignKey("AnswersId")]
public Answer Answers { get; set; }
}
public class Answer
{
[Key]
public Guid Id { get; set; }
public string Answers { get; set; }
public int Score { get; set; }
}
关系定义如下:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Question>()
.HasOne(q => q.Answers);
}
和这个简单的 LINQ:
return _context.Questions
.Include(q => q.Answers)
.FirstOrDefault(s => s.Id == id);
不过。版本升级后包含不起作用。不工作我的意思是返回值不包括答案。仅返回主实体,子实体中的所有字段均为空。
我不是 100% 确定这是否是问题所在,因为您说它之前工作正常,但可能是您的关系在 OnModelCreating
中配置不正确,因为它缺少调用 WithOne
或 WithMany
是正确的。
来自docs:
After calling this method, you should chain a call to WithMany(String) or WithOne(String) to fully configure the relationship. Calling just this method without the chained call will not produce a valid relationship.
有一个breaking change in EF 5 related to the semantics of a required nagivation property from the principal (Question) to the dependant (Answer),可能是升级库后错误行为的解释。
让我们试一试...尝试像这样配置您的关系:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Question>()
.HasOne(q => q.Answers);
.WithOne()
.IsRequired();
}