【发布时间】:2019-04-28 11:11:11
【问题描述】:
我正在尝试从数据库中返回一些值,并且我有两个类Item 和Product。 Item 包含一个 Product 和 quantity 字段。
在数据库中,有一个名为Items 的表。 DbContext的正确使用方法是什么?
因为当我尝试调用数据酶时,我收到了一个错误
MyStoreProject.Dal.Item:EntityType 'Item' 没有定义键。定义此 EntityType 的键。
items: EntityType: EntitySet 'items' 基于没有定义键的类型 'Item'。
还有其他方法可以为Item 类定义键吗?
我已经尝试找到正确的方法...所以请您帮忙
System.Data.Entity.ModelConfiguration.ModelValidationException
HResult=0x80131500
Message=在模型生成期间检测到一个或多个验证错误:MyStoreProject.Dal.Item: : EntityType 'Item' 没有定义键。定义此 EntityType 的键。
items: EntityType: EntitySet 'items' 基于没有定义键的类型 'Item'。
代码:
public class ItemDal : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Item>().ToTable("Items");
}
public DbSet<Item> items { get; set; }
}
public class Item
{
[Key]
public Product idproduct { get; set; }
[Required]
public int quantity { get; set; }
}
public class Product
{
[Key]
[Required]
[RegularExpression("^[0-9]{3}$", ErrorMessage = "Product ID must be with 4 numbers")]
public string productId { get; set; }
[RegularExpression("^[a-z]+$", ErrorMessage = "Product Name must be only Characters")]
[StringLength(50, MinimumLength = 2, ErrorMessage = "Product Name must be with a least 2 Characters or Maximum 10 Characters")]
public string name { get; set; }
[Required]
public string description { get; set; }
[Required]
[RegularExpression("^[0-9]{3}$", ErrorMessage = "Price can be with 3 numbers")]
public float price { get; set; }
[Required]
[RegularExpression("^[0-9]{3}$", ErrorMessage = "Class Code can be Only between 1-20")]
public int classCode { get; set; }
public string image { get; set; }
}
这是有异常的代码
ItemDal itemDal = new ItemDal();
Item dbitem = (from x in itemDal.items
where x.idproduct.productId.Equals(id)
select x).ToList<Item>().FirstOrDefault();
【问题讨论】:
标签: entity-framework sqlite model-view-controller dbcontext