运行我的应用程序时出现以下错误。我正在强制应用程序为我的上下文执行 DropCreateDatabaseAlways,所以我不确定为什么它会说我正在尝试使用相同的键插入多个实体。
用户和消息的链接方式可能存在问题。我不得不补充:
modelBuilder.Entity<Message>()
.HasRequired(m => m.UserSentFrom)
.WithRequiredDependent()
.WillCascadeOnDelete(false);
仅仅因为我收到有关循环引用的警告并且不得不将 willcascadeondelete 设置为 false。
如果我的设计有问题,请告诉我,但这就是我想要做的:用户有很多消息,消息有一个 FromUser 消息有很多 ToUser
任何帮助将不胜感激,因为这让我发疯。
{“检测到冲突更改。尝试插入具有相同键的多个实体时可能会发生这种情况。”}
public class User
{
public int Id { get; set; }
[Required(ErrorMessage="Username is required")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage="Email Address is required")]
[DataType(DataType.EmailAddress)]
public string UserEmailAddress { get; set; }
[DisplayFormat(DataFormatString="{0:d}",ApplyFormatInEditMode=true)]
public DateTime DateCreated { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime LastUpdated { get; set; }
public virtual ICollection<Message> Messages { get; set; }
public User()
{
Messages = new List<Message>();
}
}
public class Message
{
public int Id { get; set; }
public DateTime DateSent { get; set; }
public virtual ICollection<User> UserSentTo { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public int UserSentFromId { get; set; }
public virtual User UserSentFrom { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Message>()
.HasMany(m => m.UserSentTo).WithMany(u => u.Messages)
.Map(t => t.MapLeftKey("MessageId")
.MapRightKey("UserId")
.ToTable("MessagesUserSentTo"));
modelBuilder.Entity<Message>()
.HasRequired(m => m.UserSentFrom)
.WithRequiredDependent()
.WillCascadeOnDelete(false);
}
protected override void Seed(WebsiteGameContext context)
{
var users = new List<User>
{
new User { Username = "Admin", UserEmailAddress="admin@temp.com", DateCreated = DateTime.Now, LastUpdated = DateTime.Now},
new User { Username = "Member", UserEmailAddress="member@temp.com",DateCreated = DateTime.Now, LastUpdated = DateTime.Now}
};
users.ForEach(u => context.Users.Add(u));
context.SaveChanges();
var messages = new List<Message>
{
new Message { DateSent=DateTime.Now, Title="Sent From Admin", Body="There should be 2 users that this was sent to", UserSentFromId=users[0].Id,UserSentTo= new List<User>()},
new Message { DateSent=DateTime.Now, Title="Sent From Member", Body="There should be 1 user that this was sent to", UserSentFromId=users[1].Id,UserSentTo= new List<User>()}
};
messages.ForEach(m => context.Messages.Add(m));
context.SaveChanges();
messages[0].UserSentTo.Add(users[0]);
messages[0].UserSentTo.Add(users[1]);
messages[1].UserSentTo.Add(users[0]);
context.SaveChanges();
}