我得到的错误信息是----- MVCRegistration.Models.Post_UserProfile :: Multiplicity与关系'Post_UserProfile'中Role'Post_UserProfile_Target'中的引用约束冲突。由于“从属角色”中的所有属性都是不可为空的,因此“主体角色”的多重性必须为“1”。 MVCRegistration.Models.PostComment_UserProfile ::多重性与关系'PostComment_UserProfile'中Role'PostComment_UserProfile_Target'中的引用约束冲突。由于“从属角色”中的所有属性都不可为空,因此“主要角色”的多重性必须为“1”。 这里,MVCRegistraion是解决方案文件名。
现在,我有三个这样的课程---
public class UserProfile
{
public UserProfile()
{
this.PostComments = new HashSet<PostComment>();
this.Posts = new HashSet<Post>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string AvatarExt { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
和帖子类是这样的----
public class Post
{
public Post()
{
this.PostComments = new HashSet<PostComment>();
}
[Key]
public int PostId { get; set; }
public string Message { get; set; }
public int PostedBy { get; set; }
public System.DateTime PostedDate { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
和PostComment是----
public class PostComment
{
[Key]
public int CommentId { get; set; }
public int PostId { get; set; }
public string Message { get; set; }
public int CommentedBy { get; set; }
public System.DateTime CommentedDate { get; set; }
public virtual Post Post { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
我在USerProfile类和Post类之间配置了一对多的关系,使用流畅的api ---
modelBuilder.Entity<Post>()
.HasOptional<UserProfile>(u => u.UserProfile)
.WithMany(p => p.Posts)
.HasForeignKey(s => s.PostedBy);
和USerProfile和Post评论类之间的一对多关系就像这样-----
modelBuilder.Entity<PostComment>()
.HasOptional<UserProfile>(u => u.UserProfile)
.WithMany(p => p.PostComments)
.HasForeignKey(s => s.CommentedBy);
现在,我很沮丧地弄清楚这里发生了什么。在代码中首先创建名为PostedBy的外键是如此简单,但实体框架使事情变得更糟。不知道现在需要什么实体框架。
答案 0 :(得分:3)
正如声明所说,在一对多的结尾,即在从属结束时,你拥有不可空的财产,并且在你的流利api中,你试图使你的外键可以为空。
只需将Post类中的外键从非可空变为可为空即可 -
public int? PostedBy {get; set;}
再次在你的评论课中,你必须这样做----
pulic int? CommentedBy {get; set;}
答案 1 :(得分:1)
由于从属角色中的所有属性都不可为空,因此主要角色的多重性必须为“1”
然而:
do_stuff(Object generic_data){((cast_so_special_class)generic_data).do_something_spcial_class_specific();}
由于CommentedBy不可为空,这意味着Post注释必须具有UserProfile。您有两种方法可以解决此问题:
public int? CommentedBy {get;组; }
或
HasRequired(u =&gt; u.UserProfile)。
只需要匹配。