【问题标题】:How to deal with Foreign key relationships Entity Framework MVCEntity Framework MVC如何处理外键关系
【发布时间】:2016-12-03 06:14:15
【问题描述】:
public class UserCommentry
{
    [Key]
    public int ID { get; set; }
    [ForeignKey("AccountID")]
    public int AccountID { get; set; }
    public virtual Account account { get; set; }
    public Int64 TransferID { get; set; }
}

主键字段

public class Account
{
    [Key]
    public int ID { get; set; }
    public int code{ get; set; }
    public Int64 TransferID { get; set; }

错误:

无法将属性“AccountID”配置为导航属性。该属性必须是有效的实体类型,并且该属性应该具有非抽象的 getter 和 setter。对于集合属性,该类型必须实现 ICollection,其中 T 是有效的实体类型。

【问题讨论】:

  • 您将ForeignKey 属性放在了错误的位置。只需将其移至 account 属性的正上方即可。

标签: c# entity-framework


【解决方案1】:

简短的回答:这是因为 navigarion 属性应该是您希望它指向的类型。 如果我想与帐户建立关系,我会这样做:

public class UserCommentry
    {
        [Key]
        public int ID { get; set; }
        public Account Account{ get; set; }
        public virtual Account account { get; set; }

        public Int64 TransferID { get; set; }
    }

然后使用 OnModelCreating 让上下文知道它。你可以在这里阅读更多内容http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    相关资源
    最近更新 更多