[英]Error with primary key in one-to-one relationship using Entity Framework
I've created a database according to which the user profile is formed by the following two classes: 我创建了一个数据库,根据该数据库,用户配置文件由以下两个类组成:
public class Usr
{
[Key()]
public int UsrID { get; set; }
public virtual UsrType UsrType { get; set; }
public virtual UsrStatus UsrStatus { get; set; }
[Required]
[MaxLength(100, ErrorMessage = "Email can only contain {0} characters")]
public string UsrEmail { get; set; }
[Required]
[MaxLength(32, ErrorMessage = "Password can only contain {0} characters")]
[MinLength(8, ErrorMessage = "Password must be at least {0} characters")]
public string UsrPassword { get; set; }
}
public class UsrDetails
{
[ForeignKey("UsrID")]
[Required]
public virtual Usr Usr { get; set; }
[Required]
[MaxLength(40, ErrorMessage = "Name can only contain {0} characters")]
public string UsrName { get; set; }
[Required]
[MaxLength(40, ErrorMessage = "Surname can only contain {0} characters")]
public string UsrSurname { get; set; }
[Required]
[MaxLength(20, ErrorMessage = "Country can only contain {0} characters")]
public string UsrCountry { get; set; }
[Required]
[MaxLength(20, ErrorMessage = "City can only contain {0} characters")]
public string UsrCity { get; set; }
[Required]
[MaxLength(40, ErrorMessage = "Street can only contain {0} characters")]
public string UsrStreet { get; set; }
[Required]
public int UsrNum { get; set; }
[Required]
public int UsrPostalCode { get; set; }
}
I want to connect them by having both as primary key the UsrID
and I get an error that UsrDetails
don't have a primary key because I'm using the foreign key attribute. 我希望通过将两者作为主键
UsrID
来连接它们,并且我得到一个错误,即UsrDetails
没有主键,因为我正在使用外键属性。 Any ideas? 有任何想法吗?
You need to declare a key property in UserDetails
with the same name that you declare in the ForeignKey
attribute: 您需要在
UserDetails
声明一个与您在ForeignKey
属性中声明的名称相同的键属性:
public class UsrDetails
{
[Key]
public int UsrID{ get; set; }
[ForeignKey("UsrID")]
public virtual Usr Usr { get; set; }
}
All your entities must have a PK property. 您的所有实体都必须具有PK属性。 In this case where you are representing a one to one relationship, the PK of the dependent entity also is the FK.
在您表示一对一关系的情况下,从属实体的PK也是FK。 You can check this tutorial in case you need more info.
如果您需要更多信息,可以查看本教程 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.