Configuring a relationship that uses Table Splitting in EF Core 2

c# ef-fluent-api entity-framework entity-framework-core

Question

I'm trying to build my first Table Splitting in EF Core 2 using fluent configuration.
I have two simple entities named User and Customer and I want use them in single table named "AppUsers". So I created a simple entity classes for both:

User.cs

public partial class User
{
    public long Id { get; set; }

    public string Name { get; set; }

    public Customer Customer { get; set; }
}

And:

Customer.cs

public partial class Customer
{
    public long Id { get; set; }

    public Guid CustomerGuid { get; set; }

    public User User { get; set; }
}

Then I make changes to MyDbContext as:

MyDbContext.cs

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasOne(c => c.Customer).WithOne(c => c.User)
            .HasForeignKey<Customer>(e => e.Id);

        modelBuilder.Entity<User>().ToTable("AppUsers");
        modelBuilder.Entity<Customer>().ToTable("AppUsers");
        base.OnModelCreating(modelBuilder);
    }
}

And then I created a migration using Add-Migration "Simple_Test" without errors. So I run Update-Database that worked fine without console error but when I trying to run app getting this error:

The entity of 'User' is sharing the table 'AppUsers' with 'Customer', but there is no entity of this type with the same key value that has been marked as 'Added'

I cant understand this. I'm student just started learning about relationship configuration. Any idea please?

1
0
3/8/2018 7:32:50 PM

Accepted Answer

The issue is that each row in the database table now contains fields from two entities--one User and one Customer. This means that every time a User is created and saved, there must also be a Customer created and saved with the same Id, because the database row cannot hold only a User or only a Customer, it must have both.

I added Customer seed's in another method that's my fool. That must be in User seed's.

var user = new User(); user.Customer = new Customer { Id = user.Id }

0
3/8/2018 9:48:18 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow