我遇到的问题是,当我尝试实例化任何类时,我的实体框架仍然表现得很奇怪。我正在尝试使用默认的 usermanager 行为将数据存储在我的数据库中。一旦我在将该通知添加到应用程序用户类中可用的通知列表之前开始实例化新通知,它会持续存在这些更改并从实体框架处理错误,说明存在多重性问题,如何告知实体框架不一旦我实例化了一个类,这就是我的控制器代码:
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);
提前致谢!
答案 0 :(得分:0)
您没有任何外键可以链接AssociatedUser
。尝试使用外键添加属性以将Notification
链接到ApplicationUser
。像
public class Notification
{
//rest of properties
//change int to whatever type your primary key is in
//ApplicationUser class. I have Guid for example.
public int ApplicationUser AssociatedUserId {get;set;}
}
然后尝试修改这样的配置:
modelBuilder.Entity<Notification>()
.HasRequired(c => c.AssociatedUser)
.WithMany(c => c.Notifications)
.HasForeignKey(n=>n.AssociatedUserId);