我遇到一个问题,当我尝试实例化任何类时,我的实体框架一直表现得很奇怪。我正在尝试使用默认的 usermanager 行为将数据存储在我的数据库中。
一旦我在将该通知添加到应用程序用户类中可用的通知列表之前开始实例化新通知,它就会持续存在这些更改,并从实体框架处理错误,说明存在多重性问题 ,一旦我实例化一个类,我怎么能告诉实体框架不要保持更改cf这里是我的控制器代码:
public string AddFriend(string AddedUserId)
{
var AddedUser = UserManager.FindById(AddedUserId);
var AddingUser = UserManager.FindById(User.Identity.GetUserId());
var friendship = new Friend(AddingUser, AddedUser) { IsInvitation = true
};
AddingUser.Friends.Add(friendship);
AddedUser.Notifications.Add(new Notification(AddingUser,
"Friend Invitation",
"The user " + AddingUser.FirstName + " " + AddingUser.LastName +
"Sent you a friend invitation", friendship));
UserManager.Update(AddedUser);
UserManager.Update(AddingUser);
return "Friend was added successfully";
}
我的通知类:
[Table("Notifications")]
public class Notification
{
[Key]
public int NotificationId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
[Required]
public ApplicationUser AssociatedUser { get; set; }
public Friend AssociatedFrienship { get; set; }
public GroupMember AssociatedGroup { get; set; }
public ChannelMember AssociatedChannel { get; set; }
public Message AssociatedMessage { get; set; }
public bool Consulted { get; set; }
public Notification()
{
}
public Notification(ApplicationUser associatedUser, string title, string content, Friend associatedFriend = null, GroupMember associatedGroup = null, ChannelMember associatedChannel = null, Message associatedMessage = null)
{
AssociatedUser = associatedUser;
Title = title;
Content = content;
AssociatedChannel = associatedChannel;
AssociatedGroup = associatedGroup;
AssociatedFrienship = associatedFriend;
AssociatedMessage = associatedMessage;
Consulted = false;
}
}
我的ApplicationUser类:
public partial class ApplicationUser : IdentityUser
{
public virtual List<Notification> Notifications { get; set; }
}
我的FluentAPI代码:
modelBuilder.Entity<Notification>()
.HasRequired(c => c.AssociatedUser)
.WithMany(c => c.Notifications);
我得到的错误就行了:&gt; UserManager.Update(addedUser);它表示实体框架约束违规,关系(Qwirk.Models.Notification_AssociatedUser)的角色(Notification_AssociatedUser_Target)的多样性为1或0..1。 在此先感谢!!
答案 0 :(得分:0)
解决方案时间,在搜索错误2天后,我终于找到了它: 在我的控制器中,我必须这样做:
AddedUser.Notifications.Add(new Notification(AddedUser,
"Friend Invitation",
"The user " + AddingUser.FirstName + " " + AddingUser.LastName +
"Sent you a friend invitation", friendship));
添加了用户,而不是添加用户yaayyyyyy我觉得在这一点上真的很愚蠢lmao。