有代表模型的这个类
public class User : IHaveId
{
public User()
{
Operations = new Collection<Operation>();
}
public int Id { get; set; }
public string UserName { get; set; }
public string CardNumber { get; set; }
public string Pin { get; set; }
public double Balance { get; set; }
public bool Blocked { get; set; }
public ICollection<Operation> Operations { get; set; }
}
以及我自己的初始化器中的这个种子方法:
protected override void Seed(BankContext context)
{
var users = MockData.GetUsers();
foreach (var user in users)
{
user.Operations.Add(
new Operation
{
OperationType = OperationType.Balance,
PerformTime = DateTime.Now.AddDays(-10)
}
);
user.Operations.Add(
new Operation
{
OperationType = OperationType.GetMoney,
PerformTime = DateTime.Now.AddDays(-5),
AdditionInformation = "800"
}
);
context.Users.Add(user);
}
base.Seed(context);
}
在添加阶段出现异常:无法转换 Collection<Operation>
到操作。
有人可以解释为什么会这样吗?
对于这种情况,我是否需要在 onModelCreating 中指定任何特殊内容?
最佳答案
由于 User.Operations
应该是一个集合属性(而不是引用属性),您需要使用 HasMany
:
modelBuilder.Entity<User>()
.HasMany(a => a.Operations)
.WithOptional()
.WillCascadeOnDelete(true);
最初,您告诉 EF User.Operations
是一个引用属性,这会在您尝试为其分配集合时导致错误。
关于c# - 无法先投代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963969/