2015-11-05 58 views
1

我试图添加一些使用EntityFramework的实体。 我需要同样的模型作为图像 I need the same model as in image 我创建了两个类:属性'Dish_ID'不能用作实体上的关键属性

public class PriceOfDish 
{ 
    [Key] 
    public virtual List<Dish> Dish_ID { get; set; } 
    [Key] 
    public DateTime DateTime { get; set; } 

    public decimal Price { get; set; } 
} 
public class Dish 
{ 
    [Key] 
    public int Dish_ID { get; set; } 
    public string DishName { get; set; } 
    public string Description { get; set; } 
    public virtual FoodCategory FoodCategory_ID { get; set; } 
    public virtual Feature Feature_ID { get; set; } 

    public virtual ICollection<OrderedDishes> Orders { get; set; } 

} 

使用FluentAPI试图设置主键:

builder.Entity<PriceOfDish>() 
      .HasKey(t => new {t.Dish_ID, t.DateTime}); 

在更新DB我得到错误信息:“该物业'Dish_ID'不能用作实体'testFOef.PriceOfDish'的关键属性,因为属性类型不是有效的键类型,只有标量类型,字符串和字节[]是支持的键类型。“ 但是为什么?你能解释一下吗?感谢您的任何帮助

+0

注意到错误提到'PriceOfDish'类,而不是'Dish'类。您不能简单地使用列表作为ID。您必须为该场景寻找“复合键”。 –

回答

4

就像错误说你正在使用List<Dish>作为你的主键的类型。您必须照常使用标量类型(值类型)或byte []。

对于您来说,解决方案是创建一个具有int类型的proprerty Dish_ID

public class PriceOfDish 
{ 
    [Key] 
    public int Dish_ID { get; set; } 

    [Key] 
    public DateTime DateTime { get; set; } 

    [ForeignKey("Dish_Id")] 
    public virtual Dish Dish { get; set; } 

    public decimal Price { get; set; } 

}

+0

但EF如何从“Dish”表中找到此属性? – Eluvium

+1

它会按惯例找到它。它将查找名称为DishId或Dish_ID的proprerty。 – CodeNotFound

+0

这真的可以工作,但是用键创建的实体并且没有与“Dish”表的连接。我很抱歉这个简单的问题和我的英语不好 – Eluvium

1

你想设置一个List<Dish> Dish_ID作为表的键。 但是这不被支持。它也没有多大意义。名单Dish es将有一个单一的Price?我想你想把int Dish_ID那里