c# - 无法先投代码

标签 c# entity-framework entity-framework-6 code-first

有代表模型的这个类

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/

相关文章:

c# - 在应用程序配置文件中找不到指定的连接字符串

entity-framework - Entity Framework 从源代码管理中删除文件

c# - 如何分离未分离的输入C#

c# - 使用 Roslyn 向类添加新字段声明

ASP.NET MVC 3、Entity Framework 4。更新与许多相关的实体

mysql - 迁移到 MySQL 且指定的架构无效

c# - EF Core - NodaTime 类型的脚手架?

c# - EF Code First DbContext 仅为集合的第一个元素返回封装的实体

c# - 如何使用大众运输

c# - 使用日期时间筛选器构建 LINQ to Entities 表达式树