Asp.net mvc 多重性与角色中的引用约束冲突
我收到的错误消息如下----- MVCRegistration.Models.Post_UserProfile::多重性与关系“Post_UserProfile”中角色“Post_UserProfile_Target”中的引用约束冲突。因为从属角色中的所有属性都不可为null,所以主体角色的多重性必须为“1”。 MVCRegistration.Models.PostComment\u UserProfile::多重性与关系“PostComment\u UserProfile”中角色“PostComment\u UserProfile\u Target”中的引用约束冲突。由于从属角色中的所有属性都不可为空,因此主体角色的多重性必须为“1”。 这里,MVCRegistraion是解决方案文件名 现在,我有三节这样的课---Asp.net mvc 多重性与角色中的引用约束冲突,asp.net-mvc,entity-framework,ef-code-first,one-to-many,Asp.net Mvc,Entity Framework,Ef Code First,One To Many,我收到的错误消息如下----- MVCRegistration.Models.Post_UserProfile::多重性与关系“Post_UserProfile”中角色“Post_UserProfile_Target”中的引用约束冲突。因为从属角色中的所有属性都不可为null,所以主体角色的多重性必须为“1”。 MVCRegistration.Models.PostComment\u UserProfile::多重性与关系“PostComment\u UserProfile”中角色“PostCo
modelBuilder.Entity<PostComment>()
.HasOptional<UserProfile>(u => u.UserProfile)
.WithMany(p => p.PostComments)
.HasForeignKey(s => s.CommentedBy);
我已经使用fluentapi配置了USerProfile类和Post类之间的一对多关系---
modelBuilder.Entity()
.has可选(u=>u.UserProfile)
.有许多(p=>p.Posts)
.HasForeignKey(s=>s.PostedBy);
USerProfile和Post comment类之间的一对多关系如下-----
modelBuilder.Entity()
.has可选(u=>u.UserProfile)
.有许多(p=>p.PostComments)
.HasForeignKey(s=>s.CommentedBy);
现在,我在搞清楚这里到底发生了什么事。首先在代码中查找名称为PostedBy的外键非常简单,但实体框架让事情变得更糟。现在不知道实体框架需要什么。因为依赖角色中的所有属性都不可为空,所以主体角色的多重性必须为“1” 然而:
modelBuilder.Entity<PostComment>()
.HasOptional<UserProfile>(u => u.UserProfile)
.WithMany(p => p.PostComments)
.HasForeignKey(s => s.CommentedBy);
modelBuilder.Entity()
.has可选(u=>u.UserProfile)
.有许多(p=>p.PostComments)
.HasForeignKey(s=>s.CommentedBy);
由于CommentedBy不可为Null,这意味着Post注释必须具有UserProfile。您有两个选项可以修复此问题:
公共整数?由{get;set;}注释
或
HasRequired(u=>u.UserProfile)
它必须匹配。正如声明所说,在一对多端,即在依赖端,您的属性不可为null,而在fluent api中,您正试图使外键可为null 只需将Post类中的外键从不可为null更改为可为null,如下所示--
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; }
}
pulic int? CommentedBy {get; set;}
在你的评论课上,你必须这样做----
那么,如果您从可为空的Guid(
Guid?
)中获取此错误,该怎么办呢。还有什么要检查的吗?
modelBuilder.Entity<PostComment>()
.HasOptional<UserProfile>(u => u.UserProfile)
.WithMany(p => p.PostComments)
.HasForeignKey(s => s.CommentedBy);
public int? PostedBy {get; set;}
pulic int? CommentedBy {get; set;}