【问题标题】:MVC 4 Entity Framework - Foreign Key to UserProfileMVC 4 实体框架 - UserProfile 的外键
【发布时间】:2014-12-17 14:35:43
【问题描述】:

我使用内置的帐户控制器/模型/视图创建了一个标准的 MVC 4 应用程序。我现在尝试添加另一个控制器,但我想创建与现有用户的外键关系,但我收到错误消息:

类型“MVC4App.Models.ListingModel”的属性“CreatedBy”上的 ForeignKeyAttribute 无效。在依赖类型“MVC4App.Models.ListingModel”上找不到外键名称“UserId”。 Name 值应该是一个逗号分隔的外键属性名称列表。

上市模式代码是:

使用系统; 使用 System.ComponentModel.DataAnnotations.Schema;

namespace MVC4App.Models
{
    public class ListingModel
    {
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public string Location { get; set; }

        public string Instrument { get; set; }

        public string Genres { get; set; }

        public string Description { get; set; }

        [ForeignKey("UserId")]
        public virtual UserProfile CreatedBy { get; set; } 

        public DateTime CreatedOn { get; set; }
    }
}

我在这里缺少什么?还是有更好的方法我应该这样做?

我还假设我可以在项目中稍后向用户个人资料添加额外的属性,例如电子邮件地址或头像图像的链接?

【问题讨论】:

    标签: entity-framework-4 asp.net-mvc-4 foreign-key-relationship


    【解决方案1】:

    您必须将 UserId 添加到您的实体:

    namespace MVC4App.Models
    {
        public class ListingModel
        {
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
    
            public string Location { get; set; }
    
            public string Instrument { get; set; }
    
            public string Genres { get; set; }
    
            public string Description { get; set; }
    
            public int UserId {get; set;}
            [ForeignKey("UserId")]
            public virtual UserProfile CreatedBy { get; set; } 
    
            public DateTime CreatedOn { get; set; }
        }
    }
    

    【讨论】:

    • 不确定这是如何解决问题的,但就Code First 而言,这是不可能的。仅Only one identity column per table is allowed
    • 我意识到这有点老了,但要回答@komenge-mwandila,每张表只有一个标识列。 Id 是标识列,而 UserId 只是一个 int。当然,它是一个外键,它链接到一个可能是标识列的列,但它只是一个 int。这确实与实体框架无关,因为您希望在两个具有标识列的表之间有一个外键,但希望这有助于澄清问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    相关资源
    最近更新 更多