开发者

Weird database schema created by ef 4.1 code first

I have a model that looks like this (well not really but it has the same problem)

public class Book
{
    public int Id { get; set; }
    public ICollection<Chapter> Chapters { get; set; }
    public Chapter FirstUnreadChapt开发者_运维百科er { get; set; }
}
public class Chapter
{
    public int Id { get; set; }
    public Book Parent { get; set; }
}

And a container like this:

   public class BookContext : DbContext
    {
        public DbSet<Chapter> Chapters { get; set; }
        public DbSet<Book> Books { get; set; }
    }

Now letting this create a database itself in sql server express generate the following database tables:

CREATE TABLE [dbo].[Books](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FirstUnreadChapter_Id] [int] NULL)
CREATE TABLE [dbo].[Chapters](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Book_Id] [int] NULL,
    [Parent_Id] [int] NULL)

Now to my problem: I can't for the life of me understand why it is generating two foreign keys from Chapters to Books. The Parent_Id-column seems obvious to support the navigation property "Parent" but why the Book_Id-column?

Note: I'm using Entity Framework version 4.1.10331.0


You need to tell EF that the Parent property corresponds to the Chapters collection:

public class BookContext : DbContext
{
    public DbSet<Chapter> Chapters { get; set; }
    public DbSet<Book> Books { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Book>()
                    .HasMany(x => x.Chapters)
                    .WithRequired(x => x.Parent);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜