[英]One to one relationship with nullable foreign key in Entity Framework
I'm trying to create database relationship between two tables. 我正在尝试在两个表之间创建数据库关系。
I have redemption codes which can be free. 我有可以免费使用的兑换代码。 But one user has only one redem code. 但是一个用户只有一个兑换代码。
I created two entities: 我创建了两个实体:
public class UserProfile
{
[Key]
[ForeignKey("User")]
public int Id { get; set; }
//... other fields
public virtual RedemptionCode RedemptionCode { get; set; }
public virtual User User { get; set; }
}
public class RedemptionCode
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("UserProfile")]
public int? UserProfileId { get; set; }
public virtual UserProfile UserProfile { get; set; }
[Required]
public string Code { get; set; }
}
But when I adding a migration I have the following error: 但是,当我添加迁移时,出现以下错误:
One or more validation errors were detected during model generation: 在模型生成期间检测到一个或多个验证错误:
RedemptionCode_UserProfile_Source: : Multiplicity is not valid in Role 'RedemptionCode_UserProfile_Source' in relationship 'RedemptionCode_UserProfile'. RedemptionCode_UserProfile_Source::多重性在关系“ RedemptionCode_UserProfile”中的角色“ RedemptionCode_UserProfile_Source”中无效。 Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'. 因为从属角色属性不是关键属性,所以从属角色多重性的上限必须为'*'。
What do I really want? 我到底要什么 I want to store free redem codes in db and link one of them with new user in my system. 我想在数据库中存储免费的兑换代码,并将其中之一与系统中的新用户链接。
Here is the right code for the UserProfile
class 这是UserProfile
类的正确代码
public class RedemptionCode
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key,ForeignKey("UserProfile")]
public int Id { get; set; }
public int? UserProfileId { get; set; }
[ForeignKey("UserProfile")]
public virtual UserProfile UserProfile { get; set; }
[Required]
public string Code { get; set; }
}
You have to move the ForeignKey
from the property UserProfileId
to the navigation property UserProfile
and indicate that UserProfile is the principal in the relationship by adding the ForeignKey
attribute to the Id
of the RedemptionCode
class 您必须将ForeignKey
从属性UserProfileId
移至导航属性UserProfile
并通过将ForeignKey
属性添加到RedemptionCode
类的Id
来指示UserProfile是关系中的主体
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.