【发布时间】:2017-03-28 17:56:39
【问题描述】:
我想在Users 和Notifications 之间创建一个我认为是一对多关系的关系。
我遇到了这个问题,不知道我哪里出错了。下面是这两个类的代码:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public virtual ICollection<Notification> Notifications { get; set; }
}
public class Notification
{
public int NotificationID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime Time { get; set; }
public string ApplicationUserID { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
我上面还有以下映射:
modelBuilder.Entity<Notification>()
.HasRequired<ApplicationUser>(u => u.ApplicationUser)
.WithMany(u => u.Notifications)
.HasForeignKey(u => u.NotificationID);
我在尝试修复此问题时遇到了不同的错误,例如:
- 多重性无效
- 违反了多重性约束。关系_的角色_具有多重性1或0..1
编辑:
当我尝试为所有用户添加通知时,抛出相同的异常(违反多重约束。关系 Notification_ApplicationUser 的角色“Notification_ApplicationUser_Target”具有多重性 1 或 0..1。)正如我在此方法中所做的那样:
public void AddNotification(Notification n)
{
var roleId = context.Roles.Where(m => m.Name == "User").Select(m => m.Id).SingleOrDefault();
var users = context.Users.Where(u => u.Roles.All(r => r.RoleId == roleId)).ToList();
try
{
foreach(var user in users)
{
user.Notifications.Add(n);
}
context.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
【问题讨论】:
标签: asp.net-mvc entity-framework ef-code-first asp.net-identity