[英]ASP.Net MVC error creating model for 2 linked tables
我正在使用現有數據庫,希望將其更新為asp.net MVC4。我很難讀取兩個表的模型。 Rule和RuleApply表。
我希望使用類似於以下內容的查詢:
var rules = db.Rules.Include("RulesApply").Where(t => t.rule_active == 1).ToList();
RuleApply表沒有主鍵(它僅用作查找表)-因此,當我嘗試編譯時,出現錯誤:
EntityType'RuleApply'沒有定義鍵。 定義此EntityType的鍵。
有什么方法可以將Rule.id與RuleApply.rule_id鏈接? 還是現有表必須添加主鍵,才能使用EF / Linq等?
namespace emc.Models
{
public class Rule
{
[Key]
public int id { get; set; }
public int type_id { get; set; }
public int rule_active { get; set; }
public DateTime rule_start { get; set; }
public DateTime rule_end { get; set; }
public virtual ICollection<RuleApply> RulesApply { get; set; }
}
public class RuleApply
{
public int type_id { get; set; }
public int rule_id { get; set; }
public virtual Rule Rule { get; set; }
}
}
感謝您的任何建議,
標記
只需將key屬性添加到RuleApply
類型(按照慣例Id
將被視為Key,您無需使用KeyAttribute
屬性標記為此類)。 也可以使用ForeignKey
屬性將rule_id
屬性與Rule
鏈接:
public class RuleApply
{
public int Id; // entity should have primary key
public int type_id { get; set; }
public int rule_id { get; set; }
[ForeignKey("rule_id")]
public virtual Rule Rule { get; set; }
}
或根據現有屬性制作組合鍵:
public class RuleApply
{
[Key, Column(Order=0)]
public int type_id { get; set; }
[Key, Column(Order=1)]
public int rule_id { get; set; }
[ForeignKey("rule_id")]
public virtual Rule Rule { get; set; }
}
順便說一句,在C#中,我們使用PascalCase命名屬性。
是有一些原因,你不能讓的組合type_id
和rule_id
的主鍵RuleApply
? 如果將這些字段編入索引,事情將以更快的速度運行,而主鍵會這樣做。
我不確定100%,因為我的所有表通常都有鍵,但是我相信EF如果沒有主鍵,EF會不願更新表。 它不會知道如何從另一個記錄中分辨出來。
你可以,但是,表明EF是type_id
和rule_id
是主鍵RuleApply
甚至沒有使它所以在基礎數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.