C# 实体框架中的1:1关系
我需要C# 实体框架中的1:1关系,c#,entity-framework,foreign-key-relationship,C#,Entity Framework,Foreign Key Relationship,我需要ApplicationUser和实体框架中我自己的类之间的1:1关系 我这样做: public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { var userIdentity = await manager
ApplicationUser
和实体框架中我自己的类之间的1:1关系
我这样做:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
/*Realations*/
public virtual ICollection<Comment> Comments { get; set; }
public virtual Posts Post { get; set; }
}
public class Posts : System.Object
{
public Posts()
{
this.PostDate = DateTime.Now;
this.PostViews = 0;
this.PostPic = "d.jpg";
}
[Key]
public int PostID { get; set; }
public string PostName { get; set; }
public string PostSummery { get; set; }
public string PostDesc { get; set; }
public string PostPic { get; set; }
public DateTime PostDate { get; set; }
public int PostViews { get; set; }
public string postMetaKeys { get; set; }
public string PostMetaDesc { get; set; }
public string UserId { get; set; }
[Key, ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public int CategoryID { get; set; }
[Key, ForeignKey("CategoryID")]
public virtual Categories Category { get; set; }
public virtual ICollection<Comment> commnets {get; set;}
}
在模型生成过程中检测到一个或多个验证错误:
ApplicationUser_Post_Target::多重性在角色中无效
关系“ApplicationUser\u Post”中的“ApplicationUser\u Post\u Target”。
由于从属角色属性不是键属性,因此
依赖角色的多重性上限必须为“*”
有什么问题?将
[必需]
属性添加到Posts
类中的UserId
属性
默认情况下,字符串属性可以为Null,但由于这是外键,并且您希望需要该关系,因此必须将
UserId
属性设置为不可为Null,这可以通过添加[必需]
属性来完成。您希望用户和帖子之间的关系为1:1吗?用户只能发布一个,并且只能发布
无论如何,在EF(至少6)中,共享同一PK的两个实体之间可以建立1:1的关系。那就是PK就是FK。因此,必须将posts
的主键设置为字符串
否则,您将处于1到*关系。显示了什么其他错误?@AdilMammadov,更新了问题。我记得
IdentityUser
具有string
键。这可能是问题吗?我也将FK
声明为字符串publicstringuserid{get;set;}
您需要在哪里创建1:1
关系<代码>应用程序用户:发布?为什么对帖子使用了错误的命名?类名应为单数。集合应为复数。像这样的“public virtual Post Posts{get;set;}”。但这只是一个旁注。与您的问题相关的旁注。希望您对此给出反馈。当我将[必需]
添加到用户ID
时,我得到了第二个错误。正确。可以使用FK 1对1关联,但是,只有当它是单向的时。参考:vs。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.HasOptional(f => f.Post)
.WithRequired(s => s.ApplicationUser);
}