我在MVC3中使用实体框架代码优先与SQLCE建立类似博客的网站。 如果需要,我愿意重新设计结构,获得一些帮助会很棒。
上下文设置为:
public class BinarContext : DbContext
{
public DbSet<Member> Members { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Reply> Replies { get; set; }
public BinarContext()
{
this.Configuration.LazyLoadingEnabled = true;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Member>().HasMany(member => member.Posts)
.WithRequired(post => post.Member)
.HasForeignKey(post => post.MemberID)
.WillCascadeOnDelete();
modelBuilder.Entity<Member>().HasMany(member => member.Replies)
.WithRequired(reply => reply.Member)
.HasForeignKey(reply => reply.MemberID)
.WillCascadeOnDelete();
modelBuilder.Entity<Post>().HasMany(post => post.Replies)
.WithRequired(reply => reply.Post)
.HasForeignKey(reply => reply.PostID)
.WillCascadeOnDelete();
base.OnModelCreating(modelBuilder);
}
}
* 注意:* 我试图按照其他人的建议摆脱WillCascadeOnDelete();
,但到目前为止还没有工作。
模型是:
会员类有关于会员发布的帖子和回复的信息。
public class Member
{
public Guid ID {get; set;}
public string Username { get; set; }
public string Email { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<Reply> Replies { get; set; }
}
Post类,其中包含有关发布该成员的成员以及为其发布的已回复成员的信息。
public class Post
{
public Guid ID {get; set;}
[DataType(DataType.MultilineText)]
public string Text { get; set; }
public Guid MemberID { get; set; }
public virtual Member Member { get; set; }
public virtual ICollection<Reply> Replies { get; set; }
}
回复类,其中包含有关发布该成员的成员以及发布的帖子的信息。
public class Reply
{
public Guid ID { get; set; }
[DataType(DataType.MultilineText)]
public string Text { get; set; }
public Guid PostID { get; set; }
public Guid MemberID { get; set; }
public virtual Post Post { get; set; }
public virtual Member Member { get; set; }
}
感谢您的帮助:)
答案 0 :(得分:1)
试试这个:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Member>().HasKey(x=>x.ID)
.HasMany(x => x.Posts)
.WillCascadeOnDelete();
modelBuilder.Entity<Member>().HasKey(x=>x.ID)
.HasMany(x => x.Replies)
.WillCascadeOnDelete();
modelBuilder.Entity<Post>().HasKey(x=>x.ID)
.HasMany(x => x.Replies)
.WillCascadeOnDelete();
modelBuilder.Entity<Post>().HasKey(x=>x.ID)
.WithRequired(x => x.Member)
.WithMany(x=>x.Posts);
modelBuilder.Entity<Replies>().HasKey(x=>x.ID)
.WithRequired(x => x.Member)
.WithMany(x=>x.Replies);
modelBuilder.Entity<Replies>().HasKey(x=>x.ID)
.WithRequired(x => x.Post)
.WithMany(x=>x.Replies);
base.OnModelCreating(modelBuilder);
}