【问题标题】:E.F 6.0 Code first One to One Navigation Property ExceptionE.F 6.0 代码优先一对一导航属性异常
【发布时间】:2014-12-15 04:26:49
【问题描述】:

我正在使用 Code first 和现有数据库和 asp.net 身份实体框架发布一个非常奇怪的场景。我有一个简单的用户配置文件模型

    [Table("CSUserProfile")]
    public partial class UserProfile
    {
        [Key]
        public string Id { get; set; }

        [Required]
        [Display(Name = "FirstName")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "LastName")]
        public string LastName { get; set; }

        [Required]
        [Display(Name = "Phone")]
        public string Phone { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        [Display(Name = "Location")]
        public string Location { get; set; }

        [Required]
        [Display(Name = "HomeTown")]
        public string Hometown { get; set; }

        public byte[] BlobData { get; set; }

        [ForeignKey("fPersonLinkGID")]
        public virtual List<ProfilePic> ProfilePic { get; set; }
    }     

还有一张个人资料图片

 [Table("CSProfilePic")]
public partial class ProfilePic
{
    [Key]
    public Guid? GID { get; set; }
    public string fPersonLinkGID { get; set; }
    public byte[] BlobData { get; set; }
}

外键是 fPersonLinkGID。一切正常,但我的问题是,如果我想要这样的用户配置文件和图像之间的一对一关系

公共虚拟 ProfilePic ProfilePic { get;放; }

(这是正确的场景)我遇到了这个奇怪的异常:

类型“eUni.Model.Application.UserProfile”的属性“ProfilePic”上的 ForeignKeyAttribute 无效。在依赖类型“eUni.Model.Application.UserProfile”上找不到外键名称“fPersonLinkGID”。 Name 值应该是逗号分隔的外键属性名称列表。

我不明白为什么我会得到那个异常

【问题讨论】:

  • 在 EF 中,对于一对一的关系,键必须是相同的类型。那就是你的 ProfilePic 必须有一个 Int 作为键。对于 userId = x,您将拥有一个 profilPicId = x。
  • 键是同一类型(字符串,字符串),使用一对多关系没有问题。我的问题是一对一发生的
  • PK 必须是同一类型:GUID 与 String 不同。您可能需要同名。
  • UserProfile 中的主键是 id(字符串),ProfilePic 中的外键是 fPersonLinkGID,它也是字符串,如您所见,我在 dataannotation 属性中声明 [ForeignKey("fPersonLinkGID")] public virtual List ProfilePic { 获取;放; } 所以键是相同的类型
  • 一对一关系(与ef),FK必须是PK

标签: entity-framework exception data-annotations code-first


【解决方案1】:

您可以阅读this answer。介绍了如何通过HasRequired和WithOptional配置一对一的关系。

对于我来说,我将通过以下方式建立一对一的关系。

public class Store {
    [Key]
    public long Id { get; set; }

    public virtual Item TheItem { get; set; }

    // .... 
}

public class Item {
    // It is FK, and also PK.
    [Key, ForeignKey("TheStore")]
    public long Id { get; set; }

    // The same string in the ForeignKey attribute. Ex: ForeignKey("TheStore")
    public virtual Store TheStore { get; set; }

    // ....
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多