我需要在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;}
}
但是当我编写命令&#34; add-migration relation&#34;在Nuget
控制台内。
无法确定之间关联的主要结束 类型&#39; FinalKaminet.Models.ApplicationUser&#39;和&#39; Models.Posts&#39;。该 必须使用显式配置此关联的主要结尾 关系流畅的API或数据注释。
我还在IdentityModels
中添加了以下代码,但显示了另一个错误:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.HasOptional(f => f.Post)
.WithRequired(s => s.ApplicationUser);
}
在模型生成期间检测到一个或多个验证错误:
ApplicationUser_Post_Target :: Multiplicity在Role中无效 &#39; ApplicationUser_Post_Target&#39;在关系&#39; ApplicationUser_Post&#39;。 因为Dependent Role属性不是关键属性,所以 依赖角色的多样性的上限必须是&#39; *&#39;。
有什么问题?
答案 0 :(得分:1)
你想在用户和帖子之间建立一对一的关系吗?用户只能发布一个且仅发布?
无论如何,在EF(至少6)中,可以在共享相同PK的两个实体之间建立1对1的关系。那就是PK就是FK。因此,您必须将posts
的PK设置为字符串。
否则你处于1对*关系。
答案 1 :(得分:0)
将[Required]
属性添加到UserId
类中的Posts
属性。
默认情况下,字符串属性可以为空,但由于这是外键,并且您希望关系为必需,因此您必须将UserId
属性设置为不可为空,这可以是通过添加[Required]
属性完成。