EF Code First Relationship问题

时间:2014-10-24 08:40:08

标签: c# sql-server entity-framework ef-code-first

我目前正在使用Entity Framework Code First,但我正面临一些麻烦让这段关系正常运作..

我有以下内容:

public class StockLevel : BaseEntity
{
    public int ProductId { get; set; }

    public int StockLevel { get; set; }

    public virtual Product Product { get; set; }
}

我的产品表和实体已经在工作,但是当我开始构建StockLevel表时,我希望它包含一个Product对象,因此在StockLevel表中,将有一个ProductId外键引用产品上的产品表,但我不想在EF中修改Product实体,但是我收到以下错误:

  

必须使用关系流畅API或数据注释显式配置此关联的主要结尾。

2 个答案:

答案 0 :(得分:0)

由于错误声明您需要使用流畅的API或数据注释配置关系。我对数据注释比较熟悉,所以我会在答案中使用它们。

要指示使用ProductId设置Product属性,您需要将ForeignKey属性添加到ProductId属性:

[ForeignKey("Product")]
public int ProductId { get; set; }

这应该足以让它发挥作用。有关详细信息,请参阅MSDN article

答案 1 :(得分:0)

您可以按如下方式实现get和set方法:

public string ProductName
{
    get
    {
        if (this.yourEntityReference.EntityKey == null) return "";
        else return (string)this.yourEntityReference
            .EntityKey.EntityKeyValues[0].Value;
    }
    set
    {
        this.yourEntityReference.EntityKey
           = new EntityKey("YourDB.YourTable", "ColumnName", value);
    }
}