我使用EF Core 7.0中的功能,该功能允许使用带有参数化构造函数的实体,如here所述.
然而,当涉及到 Select 使用哪个构造函数时,我不理解EF Core的一些行为.
例如,我有一个具有只读ID的实体,因此有一个创建构造函数,它生成id和一个以ID为参数的重构构造函数.
public class Poll
{
public Guid Id { get; }
public string Name {get;set;}
public DateTime ExpirationDate { get; set; }
public List<Vote> Votes { get; set; }
public List<DateTime> dates {get;set;} = new List<DateTime>();
public Poll(string name, List<DateTime> dates) : this(
Guid.NewGuid(),
name,
new List<Vote>(),
dates,
DateTime.UtcNow.AddMonths(2)
)
{
}
public Poll(Guid id, string name, List<DateTime> dates, DateTime expirationDate)
{
Name = name;
Id = id;
Dates = dates;
ExpirationDate = expirationDate;
}
}
具有以下模型绑定:
modelBuilder.Entity<Poll>(entity =>
{
entity.HasKey(poll => poll.Id);
entity
.Property(poll => poll.Id)
.ValueGeneratedNever();
entity.Property(poll => poll.Name);
entity.Property(poll => poll.Dates);
entity.Property(poll => poll.ExpirationDate);
});
当查询这个实体时,EF Core将调用第一个(创建)构造函数,而我希望(根据文档,我认为这是合乎逻辑的),它宁愿使用第二个(重构)构造函数. 根据文档,它为什么不使用带有每个映射属性的参数的构造函数:
但是,如果EF Core找到其参数名称和类型与映射属性的参数名称和类型匹配的参数化构造函数,则它将使用这些属性的值调用该参数化构造函数,而不会显式设置每个属性.
编辑:通过删除第一个构造函数进行了试验,它抛出了一个异常,说明votes
参数无法绑定到属性.取下它的时候,它起作用了.然而,当添加回我的第一个构造函数时,EF仍然使用它而不是另一个,所以问题仍然存在.