Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8663815
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T17:04:56+00:00 2026-06-12T17:04:56+00:00

To illustrate my problem, suppose I have a data model where I have a

  • 0

To illustrate my problem, suppose I have a data model where I have a collection of Books, each of which has one or more Drafts, and also a “current” Draft. I’d like my model to look something like this:

class Book
{
    public int Id { get; set; }

    public string Title { get; set; }

    public virtual ICollection<Draft> Drafts { get; set; }

    public virtual Draft CurrentDraft { get; set; }
}

class Draft
{
    public int Id { get; set; }

    public virtual int BookId { get; set; }
    public virtual Book Book { get; set; }

    public string Description { get; set; }
}

I have a DbContext that looks like this:

class TestDbContext : DbContext
{
    public DbSet<Book> Books { get; set; }
    public DbSet<Draft> Drafts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        base.OnModelCreating(modelBuilder);
    }
}

…and a simple program like this:

static void Main(string[] args)
{
    Database.SetInitializer<TestDbContext>(new DropCreateDatabaseAlways<TestDbContext>());

    using (var db = new TestDbContext())
    {
        var book = new Book() { Title = "War and Peace", Drafts = new List<Draft>() };


        var draft1 = new Draft() { Book = book, Description = "First Draft" };

        book.Drafts.Add(draft1);


        var draft2 = new Draft() { Book = book, Description = "Second Draft" };

        book.Drafts.Add(draft2);


        book.CurrentDraft = draft2;


        db.Books.Add(book);

        db.SaveChanges();


        foreach (var b in db.Books)
        {
            Console.WriteLine("Book {0}: {1}", b.Id, b.Title);

            foreach (var d in book.Drafts)
                Console.WriteLine("\tDraft ID {0}: {1} from Book ID {2}", d.Id, d.Description, d.BookId);

            Console.WriteLine("Current draft has ID {0}", b.CurrentDraft.Id);
        }

        Console.ReadKey();
    }
}

When the DB is created by EF, it looks like this:

database schema

[I’m not wild about the extra Book_Id column, but I could live with it if it worked.]

Sadly, when I run the test program, it fails at the SaveChanges call, with an exception:

An error occurred while saving entities that do not expose foreign key
properties for their relationships. The EntityEntries property will
return null because a single entity cannot be identified as the source
of the exception. Handling of exceptions while saving can be made
easier by exposing foreign key properties in your entity types. See
the InnerException for details.

I’ve tried messing about with the fluent API in my OnModelCreating, but when I try to configure it that way it gets confused by the fact that there are two FK relationships between Books and Drafts. I’m not familiar enough with the fluent stuff (or EF generally) to know how to do it properly.

Is this even possible in EF code first?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T17:04:58+00:00Added an answer on June 12, 2026 at 5:04 pm

    Your inner exception is that EF can’t figure out the order to save things to the database to create something properly. If you call save changes in multiple places to force the order your test app will work:

                var book = new Book() { Title = "War and Peace", Drafts = new List<Draft>() };
                db.Books.Add(book);
                db.SaveChanges();
                var draft1 = new Draft() { Book = book, Description = "First Draft" };
                book.Drafts.Add(draft1);
                var draft2 = new Draft() { Book = book, Description = "Second Draft" };
                book.Drafts.Add(draft2);
                book.CurrentDraft = draft2;
                db.SaveChanges();
    

    Regarding the second book_id – you could use this fluent:

            modelBuilder.Entity<Book>()
                .HasMany(b => b.Drafts)
                .WithRequired(d => d.Book)
                .HasForeignKey(d => d.BookId);
    
            modelBuilder.Entity<Book>()
                .HasOptional(b => b.CurrentDraft)
                .WithOptionalDependent()
                .Map(m => m.MapKey("CurrentDraftId"));
    

    which produces this database:

    enter image description here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

An application specific example to illustrate my immediate problem: I have a metadata provider
Hopefully, this fictitious example will illustrate my problem: Suppose you are writing a system
I'll try to illustrate my problem by the following example: I have linux kernel
Using a basic example to illustrate my problem I have 2 near-identical bits of
I've made a simple project to illustrate my problem. I have a user control
I have simplified my code to illustrate the problem. function SnakeGame () { this.snakeDirection
To illustrate my problem I will give you an example: I have UTF-8 encoded
I have a demo here to illustrate my problem http://www.ttmt.org.uk/ It's just a simple
I have a relatively -positioned div, which has overflow: auto set. Inside that, I
I have created an example below to illustrate the problem I'm having. Basically, when

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.