我目前正在使用 Windows 窗体探索实体框架,同时遵循 官方文档 我遇到了这段代码 这会给出编译时错误:
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();
this.contextDB.Entry(category).Collection(a => a.Products).Load();
}
}
}
CS1660 无法将 lambda 表达式转换为类型“INavigationBase”,因为它不是委托类型。
错误出现在 a => a.Products 中。
编辑:这是我的数据库上下文类
internal class ContextDB : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<ProductCategory> categories { get; set; }
//public DbSet<PurchaseOrder> purchases { get; set; }
// public DbSet<cate>
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(
新产品 { ProductId = 1, CategoryId = 1, Name = "Cheddar", Price = 50 }, 新产品 { ProductId = 10, CategoryId = 1, Name = "Parmesan" }, 新产品 { ProductId = 12, CategoryId = 2, Name = "Beef" }, 新产品 { ProductId = 13, CategoryId = 2, Name = "Chicken" }, 新产品 { ProductId = 17, CategoryId = 2, Name = "Mutton" }, 新产品 { ProductId = 21, CategoryId = 3, Name = "Salmon" }, 新产品 { ProductId = 22,CategoryId = 3,Name =“Tuna”} ); } }
您至少错过了教程的一个重要部分,
DataBoundItem
返回一个object
,您需要将其转换为Category
才能继续:
var category = (Category)this.dgvCategories.CurrentRow.DataBoundItem;
DbContext.Entry<TEntity>(TEntity)
,它返回通用的 EntityEntry<TEntity>
,它允许将 lambda 传递给像 Collection
这样的方法。