c# - 为 2 个链接表创建模型的 ASP.Net MVC 错误

标签 c# asp.net-mvc linq entity-framework

我正在使用现有数据库,希望更新到 asp.net MVC 4。我在为其中两个表创建模型时遇到了困难。规则和规则应用表。

我希望使用类似这样的东西来查询它:

var rules = db.Rules.Include("RulesApply").Where(t => t.rule_active == 1).ToList();

RuleApply 表没有主键(它只是用作查找表)- 所以当我尝试编译时,出现错误:

EntityType 'RuleApply' has no key defined. Define the key for this 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; }    
}

BTW 在 C# 中,我们对属性使用 PascalCase 命名。

关于c# - 为 2 个链接表创建模型的 ASP.Net MVC 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15359177/

相关文章:

C#:减少健全性检查中的线路噪音

c# - 一个asp.net页面结构问题

c# - 应用程序似乎有两个 session cookie

asp.net-mvc - 当 id 为 null 时,ASP.NET MVC 抛出错误

c# - LINQ to SQL 默认值

.net - 使用 LINQ 获取列表中匹配值的索引

c# - ASP 中的异步 Web 服务。网络MVC

c# - PagedList.Mvc 返回表中的所有记录

c# - 如果项目文本为空,则跳过部分查询

c# - 线程安全的惰性初始化器;交换 Func<> 是一个好主意吗?