简体   繁体   中英

Entity Framework Code-First One-To-One Relationship

I have two database tables:

Customers

  • CustomerId (PK)
  • Name
  • ...

CustomerSettings

  • CustomerId (PK)
  • Setting1
  • Setting2
  • ...

Is it possible to have these classes using code-first? If so, what is the fluent mapping?

public class Customer
{
    public int CustomerId { get; set; }
    public int Name { get; set; }
    public CustomerSetting CustomerSetting { get; set; }
}

public class CustomerSetting
{
    public int CustomerId { get; set; }
    public int Setting1 { get; set; }
    public int Setting2 { get; set; }
    public Customer Customer { get; set; }
}

I personally don't like one-to-one tables. After all, why not just add the setting columns to the customer table? Unfortunately, this is what I need to develop against. I can't figure the correct code-first mappings for such a scenario. Thanks for your help.

If you are going for code first and want to have both Customer And CustomerSettings classes, but only a single table for both, as your post suggests , I would use complex types. see a good example here:

http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx

So , your object model should look like this (I've not tested it):

public class Customer
{
    public Customer()
    {
        CustomerSetting= new CustomerSetting();
    }

    public int CustomerId { get; set; }
    public int Name { get; set; }
    public CustomerSetting CustomerSetting { get; set; }
}

[ComplexType]
public class CustomerSetting
{
    public int CustomerId { get; set; }
    public int Setting1 { get; set; }
    public int Setting2 { get; set; }
    public Customer Customer { get; set; }
}

Your model classess are correct, if you want you can add this to your model builder to specify which table is the "main one":

.Entity<Customer>()
.HasOptional(c => c.CustomerSetting)
.WithRequired(u => u.Customer);

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