Entity framework E.F 6.0代码第一对一导航属性异常
我发布了一个非常奇怪的场景,首先使用现有数据库和asp.net标识实体框架的代码。我有一个简单的userprofile模型Entity framework E.F 6.0代码第一对一导航属性异常,entity-framework,exception,data-annotations,code-first,Entity Framework,Exception,Data Annotations,Code First,我发布了一个非常奇怪的场景,首先使用现有数据库和asp.net标识实体框架的代码。我有一个简单的userprofile模型 [Table("CSUserProfile")] public partial class UserProfile { [Key] public string Id { get; set; } [Required] [Display(Name = "FirstName")]
[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; }
}
外键是fPersonLinkGID。一切都很好,但我的问题是,如果我想在userprofile和图像之间建立一对一的关系,就像这样
公共虚拟配置文件pic{get;set;}
(这是正确的情况)我遇到了一个奇怪的例外:
类型“eUni.Model.Application.UserProfile”的属性“ProfilePic”上的ForeignKeyAttribute无效。在依赖类型“eUni.Model.Application.UserProfile”上找不到外键名“fPersonLinkGID”。名称值应为以逗号分隔的外键属性名称列表
我不明白为什么我会得到这个例外,你可以读到。它介绍了如何通过HasRequired
和with optional
配置一对一关系
对我来说,我将通过以下方式建立一对一的关系
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; }
// ....
}
在EF中,对于一对一关系,键必须是相同类型的。这就是你的ProfilePic必须有一个Int作为键。对于userId=x,您将拥有profilPicId=x。键的类型相同(string,string)。使用一对多关系没有问题。我的问题发生在一对一PK中PK必须是同一类型:GUID与字符串不同。您可能需要相同的名称。UserProfile中的主键是id(string)ProfilePic中的外键是fPersonLinkGID,这也是string,正如您可以看到我在dataannotation atribute[ForeignKey(“fPersonLinkGID”)]公共虚拟列表ProfilePic{get;set;}中声明的一样,因此这些键在一对一关系中是相同的类型(带有ef),FK必须是PK
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; }
// ....
}