首先遇到EF代码和mvc 3.0关系的问题

时间:2012-11-05 05:21:53

标签: asp.net-mvc-3 ef-code-first many-to-many datacontext circular-reference

运行我的应用程序时出现以下错误。我强迫应用程序为我的上下文执行DropCreateDatabaseAlways所以我不确定为什么它会说我试图插入具有相同键的多个实体。

用户和消息的链接方式可能存在问题。我不得不补充道:

                modelBuilder.Entity<Message>()
                    .HasRequired(m => m.UserSentFrom)
                    .WithRequiredDependent()
                    .WillCascadeOnDelete(false);

因为我收到了关于循环引用的警告,并且不得不将willcascadeondele设置为false。

如果我的设计有问题,请告诉我,但这就是我要做的事情: 用户有很多消息, 消息有一个FromUser 消息有许多ToUsers

任何帮助都将受到赞赏,因为这让我发疯。

{“检测到冲突的更改。尝试插入具有相同密钥的多个实体时可能会发生这种情况。”}

    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();
            }

1 个答案:

答案 0 :(得分:0)

让它改变2件事。 首先删除Users中的messages属性,然后创建MessagesSend和MessagesReceived属性。然后像这样制作映射:

        modelBuilder.Entity<Message>().HasMany(t => t.UserSentTo)
            .WithMany(t => t.MessagesReceived)
            .Map(m =>
            {
                m.ToTable("MessagesUserSentTo");
                m.MapLeftKey("MessageId");
                m.MapRightKey("UserId");
            });

        modelBuilder.Entity<Message>().HasRequired(t => t.UserSentFrom)
            .WithMany(t => t.MessagesSend)
            .HasForeignKey(d => d.UserSentFromId)
            .WillCascadeOnDelete(false);