EFCore Map 2 entities to same table

前端 未结 3 451
渐次进展
渐次进展 2020-12-11 02:27

I\'m trying to use DDD with EFCore and I am struggling to find a way to map 2 POCOs from different context that represent the same entity to the same table.

I have a

3条回答
  •  猫巷女王i
    2020-12-11 03:05

    The main cause of issue is, EF Core cannot figure out how to use same table for 2 different entities. There is lack of data in mapping, once you fill that in, it works as expected.

    First you will need to define how are they related to each other. Sharing same table with same PK does not have Foreign Key defined on server side but there is still intrinsic relationship between both entities which is one-to-one and using PK as FK. Once you define relationship, you will see that it works and both entities are mapped to same table. (Just like how owned entities are mapped to same table). This may not be end of mapping for your case though. Since from EF perspective they are still 2 different entities, except for Id (or PK property), they will have own columns to store data. But what if you have columns which are common in both the context (like Email in your scenario). In such case, you would need to provide mapping for those additional column too. If you map them to same column explicitly, they will start sharing the column in database. Overall the code would look like this.

    namespace UserContext
    {
        public class User
        {
            public int Id { get; set; }
            public string Email { get; set; }
            // Other properties
        }
    }
    
    namespace OrderContext
    {
        public class User
        {
            public int Id { get; set; }
            public string Email { get; set; }
        }
    }
    
    // In OnModelCreating method
    modelBuilder.Entity(u =>
    {
        u.ToTable("User");
        u.Property(e => e.Email).HasColumnName("Email");
        // Configuration for other properties
    });
    
    modelBuilder.Entity(u =>
    {
        u.ToTable("User");
        u.Property(e => e.Email).HasColumnName("Email");
        u.HasOne().WithOne().HasForeignKey(e => e.Id);
    });
    

    Above code creates single table with shared columns and should work as expected. You can add more entities in the same table if you want by following same configuration. Here, I used User from UserContext as principal side but you can use any side. The main reasoning for me was, UserContext.User will be the entity which will be added when adding new User. Entities sharing the table do not have to be subset either. But there will be columns for additional properties which are not shared.

提交回复
热议问题