我正在创建一个示例ASP.NET MVC Web应用程序,我正在遵循数据库的代码优先方法.我想创建产品表和事务表,另外我想通过迁移包含一些示例数据,但是当我尝试执行Update-
Database时,我收到了标题中提到的错误消息.我确切地知道错误发生的原因,那是因为我使用List< Product>,如下所示.但是,我不知道如何解决问题,而交易应包括一个或多个产品.我的代码段可以在下面找到.
public class Product { public int ProductID { get; set; } public string Name { get; set; } } public class Transaction { public int TransactionID { get; set; } public List<Product> Products { get; set; } }
我还在IdentityModels.cs文件中添加了以下代码行:
public DbSet<Product> Products { get; set; } public DbSet<Transaction> Transactions { get; set; }
最后,我的Configuration.cs文件包含迁移,如下所示:
public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } protected override void Seed(MyApp.Models.ApplicationDbContext context) { var pr = new List<Product>(); pr.Add(new Product { Name = "Book" }); pr.Add(new Product { Name = "Table" }); pr.Add(new Product { Name = "Chair" }); pr.ForEach(i => context.Products.AddOrUpdate(p => p.Name,i)); context.SaveChanges(); context.Transactions.AddOrUpdate( t => t.Products,new Transaction { Products = new List<Product>(pr.Where(p => p.Name == "Book" || p.Name == "Table")) },new Transaction { Products = new List<Product>(pr.Where(p => p.Name == "Chair" || p.Name == "Book" || p.Name == "Table")) } ); context.SaveChanges(); }
解决方法
问题是AddOrUpdate方法的第一个参数,即identifierExpression.您应该在那里提供原始类型,它确定您何时需要更新以及何时添加.如果数据库中的行与identifierExpression匹配,则它将使用您提供的新行进行更新.如果没有,新的将插入到数据库中.
您使用t.Products作为标识符,这意味着,当您添加的产品具有与其中一个数据库行相同的产品时,应该进行更新,这可能不正确,因为Products不具有基本类型.因此,您可以提供基本类型属性或根本不使用此参数(这意味着将插入所有项目).
context.Transactions.AddOrUpdate( //t => t.Products,//comment this new Transaction { Products = new List<Product>( pr.Where(p => p.Name == "Book" || p.Name == "Table")) },new Transaction { Products = new List<Product>( pr.Where(p => p.Name == "Chair" || p.Name == "Book" || p.Name == "Table")) } );
建议
从Seed方法可以推断出Transaction和Product之间的关系是多对多的.如果是这种情况,您应该为EF指定它.根据您当前的模型,这种关系是一对多的.
您可以像这样更改它(在Context类中):
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Transaction>().HasMany(x => x.Products).WithMany(); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。