【问题标题】:EF Code First Relationship issueEF 代码优先关系问题
【发布时间】:2014-10-24 08:40:08
【问题描述】:

我目前正在使用 Entity Framework Code First,但在使关系正常工作时遇到了一些麻烦..

我有以下:

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

    public int StockLevel { get; set; }

    public virtual Product Product { get; set; }
}

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

必须使用关系流式 API 或数据注释显式配置此关联的主体端。

【问题讨论】:

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


    【解决方案1】:

    由于错误状态,您需要使用 fluent API 或 Data Annotations 配置关系。我对数据注释比较熟悉,所以我会在回答中使用它们。

    要表明 Product 属性是使用 ProductId 设置的,您需要将 ForeignKey 属性添加到您的 ProductId 属性:

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

    这应该足以让它发挥作用。请参阅MSDN article 了解更多信息。

    【讨论】:

      【解决方案2】:

      您可以按如下方式实现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);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-31
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 2012-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多