【问题标题】:Entity Framewok: Is it possible to duplicate an entity and create an alias for it?实体框架:是否可以复制实体并为其创建别名?
【发布时间】:2016-06-22 18:35:28
【问题描述】:

在我的模型中,我有一个带有自关联的 [Customer] 表:

1 [客户] 可能有 1 [赞助商],赞助商是客户。

在 EF 6 中,我想知道是否可以将实体 Customer 拆分为两个单独的实体 [Customer] 和 [Sponsor] 并为它们分配同一个表?

谢谢

【问题讨论】:

    标签: asp.net entity-framework visual-studio


    【解决方案1】:

    你可以继承实体来做一个别名考虑这个例子:

    public class Person
    {
        public int ID {get;set;}
        // your shared properties here
    }
    
    public class Customer: Person
    {
        // additional properties such as
        public virtual Sponsor Sponsor {get;set;} 
    }
    
    public class Sponsor : Person
    {
        // this could be have own properties or not
    }
    

    现在你的DbContext 可能是这样的:

    public class MyDbContext:DbContext
    {
        public IDbSet<Person> Persons{get;set;}
        // optionally you could add child objects
        public IDbSet<Customer> Customers{get;set;}
        public IDbSet<Sponsor> Sponsors{get;set;}
    }
    

    由于使用继承EF,只需为您的实体创建一个表。但是你有 3 个单独的班级。

    【讨论】:

    • 我必须创建实体 Person 吗?我只想将客户作为根类别。
    • 不,这只是一个例子。您只能有 2 个实体从另一个继承。在这种情况下,您可以省略 person 实体并直接从客户那里继承赞助商。
    【解决方案2】:

    是的,你可以

        public class Customer
        {
            public int ID {get;set;}
            //all your columns goes here
            ///these 2 lines for foreign key mapping except sponsor
            public virtual Customer Sponsor {get;set;} 
            public virtual IList<Customer> CustomerList{get;set;}
        }
    

    在你的 DbContext 中

    public DbSet<Customer> Customers{get;set;}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-30
      • 1970-01-01
      相关资源
      最近更新 更多