Asp.net-Mvc-3

EF 4.1 - 模型關係

  • March 18, 2011

我正在嘗試使用 EF 4.1 的 RC 版本創建一個快速的 ASP.NET MVC 3 應用程序。我有兩個模型:

public class Race
{
   public int RaceId { get; set; }
   public string RaceName { get; set; }
   public string RaceDescription { get; set; }
   public DateTime? RaceDate { get; set; }
   public decimal? Budget { get; set; }
   public Guid? UserId { get; set; }
   public int? AddressId { get; set; }

   public virtual Address Address { get; set; }
}

public class Address
{
   public int AddressId { get; set; }
   public string Street { get; set; }
   public string StreetCont { get; set; }
   public string City { get; set; }
   public string State { get; set; }
   public string ZipCode { get; set; }

   public virtual Race Race { get; set; }
}

嘗試插入新 Race 時出現以下錯誤:

無法確定類型“rcommander.Models.Race”和“rcommander.Models.Address”之間關聯的主體端。此關聯的主體端必須使用關係流式 API 或數據註釋顯式配置。

它不應該自動將 RaceId 辨識為 Races 表的主鍵,將 AddressId 辨識為 Addresses 表的 FK 嗎?我錯過了什麼嗎?

謝謝!

這裡的問題似乎是 EntityFramework 無法辨識外鍵的位置,因為您在兩個對像中都持有交叉引用。不確定你想要實現什麼,我可能會建議這樣的事情:

public class Race
{
 public int RaceId { get; set; }
 public string RaceName { get; set; }
 public string RaceDescription { get; set; }
 public DateTime? RaceDate { get; set; }
 public decimal? Budget { get; set; }
 public Guid? UserId { get; set; }

 public int? AddressId { get; set; }
 public virtual Address Address { get; set; }
}

public class Address
{
 public int AddressId { get; set; }
 public string Street { get; set; }
 public string StreetCont { get; set; }
 public string City { get; set; }
 public string State { get; set; }
 public string ZipCode { get; set; }
}

在第二個實體中跳過對 Race 的引用。

引用自:https://stackoverflow.com/questions/5352059