Map derived type to the same table in EF

后端 未结 3 1262
刺人心
刺人心 2021-01-23 23:11

The following simple code example illustrates the scenario in question. I have a Person entity, which is simply mapped to the Person table in the DB. I am using the default Enti

相关标签:
3条回答
  • 2021-01-23 23:21

    Have you tried using composition instead of inheritance?

    public class PersonViewModel {
      public Person Person { get; }
      public int? MyViewProperty { get; set; }
      // ...
    }
    

    Unless there's a really good reason I would never transfer that object to your service however. To me that looks like a client side object only. What's the point of having GUI properties transmitted to the server when they're not stored in the database anyway? Isn't it enough to just get the Person and send that to the server for update?

    0 讨论(0)
  • 2021-01-23 23:29

    You can add your properties to the class and "ignore" them for the entity framework using the modelBuilder, looks like you doing code first development. For that options have a look at the modelBuilder =>

        public class Db : DbContext
        {
          public DbSet<MyClass> MyClasses{ get; set; }
    
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
            modelBuilder.Entity<MyClass>().Ignore(x => x.MyProperty);
          }
        }
    

    hope this helps!

    0 讨论(0)
  • 2021-01-23 23:35

    I don't think inheritance is the right answer to this. Is it true that 'PersonDetail' is-a Person? I would choose for creating a PersonDetail class and adding a property in the partial class that points to an instance of the PersonDetail class.

    That way you can check on your client side if the PersonDetail is set by the server by just checking if the property != null.

    0 讨论(0)
提交回复
热议问题