简体   繁体   中英

1 to 0..1 Relationship In Entity Framework

I want to create the following relationship. Obviously this is painfully basic but I'm falling at the first hurdle thanks to EF. In my database SubForm 's primary key, Id , is a foreign key referencing Application.Id (enforcing the relationships). When I add a new Application EF complains that I don't have a SubForm_Id row, I don't want this as this would be obviously be a duplicate of the primary key. Can I add some annotations to the model to sort this out?

This brings me to another issue, if I want to add a new Application with a new SubForm to the database at the same time - how could I get the Application Id (it is defined in the db as an auto-increment int) to set it on the SubForm object, or can EF do this for me?

Help would be appreciated.

EF by convention assumes that your Application table has a scalar property SubForm_Id when you have a navigational property of type SubForm . You need to explicitly configure the Shared Primary Key mapping.

public class MyContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         modelBuilder.Entity<Application>()
           .HasOptional(a => a.SubForm)
           .WithRequired(s => s.Application);
    }
 }

You can insert both as follows

var app = new Application();
var subForm = new SubForm { Application = app };
db.SubForms.Add(subForm);
db.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM