无法先投码
Unable to cast code first
有这个class代表模型
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; }
}
以及我自己的 Initializer 中的这个种子方法:
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 中指定任何特殊内容吗?
好的,我发现了问题,
因为我认为在发布的代码之外有一个原因。
在我的 BankContext class 我有
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.Operations)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
那一些对此有多大影响。谁能解释一下那是怎么影响的?
因为User.Operations
应该是一个集合属性(而不是引用属性),你需要使用HasMany
:
modelBuilder.Entity<User>()
.HasMany(a => a.Operations)
.WithOptional()
.WillCascadeOnDelete(true);
最初,您告诉 EF User.Operations
是一个引用 属性,当您尝试向其分配集合时会导致错误。
有这个class代表模型
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; }
}
以及我自己的 Initializer 中的这个种子方法:
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 中指定任何特殊内容吗?
好的,我发现了问题, 因为我认为在发布的代码之外有一个原因。 在我的 BankContext class 我有
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.Operations)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
那一些对此有多大影响。谁能解释一下那是怎么影响的?
因为User.Operations
应该是一个集合属性(而不是引用属性),你需要使用HasMany
:
modelBuilder.Entity<User>()
.HasMany(a => a.Operations)
.WithOptional()
.WillCascadeOnDelete(true);
最初,您告诉 EF User.Operations
是一个引用 属性,当您尝试向其分配集合时会导致错误。