EF Core WinForms开发遇CS1660错误:Lambda无法转为INavigationBase
跟随微软官方文档学习WinForms结合Entity Framework Core开发时,出现编译错误,报错代码如下:
private void dgvCategories_SelectionChanged(object sender, EventArgs e) { if(this.contextDB != null && this.dgvCategories.CurrentRow !=null) { var category = this.dgvCategories.CurrentRow.DataBoundItem; if(category != null) { this.contextDB.Entry(category).Collection(a => a.Products).Load(); } } }
错误信息:
CS1660 Cannot convert lambda expression to type 'INavigationBase' because it is not a delegate type
错误定位在a => a.Products处。
补充的DB Context类代码:
internal class ContextDB : DbContext { public DbSet<Product> Products { get; set; } public DbSet<ProductCategory> categories { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=products.db"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<ProductCategory>().HasData( new ProductCategory { CategoryId = 1, Name = "Cheese" }, new ProductCategory { CategoryId = 2, Name = "Meat" }, new ProductCategory { CategoryId = 3, Name = "Fish" }, new ProductCategory { CategoryId = 4, Name = "Bread" } ); modelBuilder.Entity<Product>().HasData( new Product { ProductId = 1, CategoryId = 1, Name = "Cheddar", Price = 50 }, new Product { ProductId = 10, CategoryId = 1, Name = "Parmesan" }, new Product { ProductId = 12, CategoryId = 2, Name = "Beef" }, new Product { ProductId = 13, CategoryId = 2, Name = "Chicken" }, new Product { ProductId = 17, CategoryId = 2, Name = "Mutton" }, new Product { ProductId = 21, CategoryId = 3, Name = "Salmon" }, new Product { ProductId = 22, CategoryId = 3, Name = "Tuna" } ); } }
解决方法
修正类型推断问题:
category变量被默认推断为object类型,contextDB.Entry(object)返回的EntityEntry没有接受lambda表达式的Collection重载,必须明确转换为实体类型。
修改变量声明:var category = (ProductCategory)this.dgvCategories.CurrentRow.DataBoundItem;补充导航属性定义:确保
ProductCategory类中存在正确的一对多导航属性,EF Core才能识别a => a.Products:public class ProductCategory { public int CategoryId { get; set; } public string Name { get; set; } // 定义一对多导航属性 public ICollection<Product> Products { get; set; } = new List<Product>(); }完善Product类关联:同时确认
Product类包含对应的外键和多对一导航属性:public class Product { public int ProductId { get; set; } public int CategoryId { get; set; } public string Name { get; set; } public decimal? Price { get; set; } // 定义多对一导航属性 public ProductCategory Category { get; set; } }
内容的提问来源于stack exchange,提问作者Muhammad Faizan Khan
相关产品推荐
相关产品推荐

