我正在使用教程中的代码来尝试我在实际项目中需要的东西。我的DataBase
中有一张桌子,其中包含很多(16)Foreign Keys
我需要使用DataBase
重新创建整个ADO.NET EF
,现在我对此很不满意特殊案例。这是我用于测试目的的代码:
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
//public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
//public int BlogId1 { get; set; }
public virtual Blog Blog1 { get; set; }
//public int BlogId2 { get; set; }
public virtual Blog Blog2 { get; set; }
//public int BlogId3 { get; set; }
public virtual Blog Blog3 { get; set; }
//public int BlogId4 { get; set; }
public virtual Blog Blog4 { get; set; }
}
我评论了int
属性,因为我似乎不需要它们。执行此代码我得到以下内容:
所以目前有两件事让我感到担忧 - 这是在一张桌子上添加多个Foreign Keys
的方式,如果是这样的话 - 两行用红色加下划线 - 为什么我有Blog_BlogId
和在我得到预期的Blog_BlogId1
之前Blog1_.., Blog2_...
?
答案 0 :(得分:0)
好的,我从这里得到解决方案的帖子丢失了,但在这种特殊情况下,它似乎是某种命名约定我必须取消注释注释代码并更改名称而不使用数字或下划线。然后在OnModelCreating
事件中,根据需要多次添加此代码:
modelBuilder.Entity<Post>().HasRequired(c => c.Blog)
.WithMany(m => m.Posts)
.HasForeignKey(c => c.BlogId)
.WillCascadeOnDelete();
modelBuilder.Entity<Post>().HasRequired(c => c.Blogged)
.WithMany()
.HasForeignKey(c => c.BloggedId)
.WillCascadeOnDelete(false);
请注意,每次添加外键的新记录时,我都会更改属性名称和类实例名称。