EF6:如何从多个表中创建自定义实体

时间:2014-03-17 23:14:03

标签: entity-framework split dbcontext

使用Northwind数据库,我使用EF6生成了该表中的所有实体。

现在我想创建一个额外的自定义实体,它不是现有的表,但它从三个现有表中提取数据。自定义实体是" OrderCustomized"。

public class OrderCustomized
{
    public int OrderID { get; set; }
    public DateTime? OrderDate { get; set; }
    public string CustomerID { get; set; }
    public string CustomerContactName { get; set; }
    public string CustomerPhone { get; set; }
    public int? EmployeeID { get; set; }
    public string EmployeeLastName { get; set; }
    public string EmployeeFirstName { get; set; }
}

public partial class NorthwindEntities : DbContext
{
    public NorthwindEntities()
        : base("name=NorthwindEntities")
    {
        this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //throw new UnintentionalCodeFirstException();

        modelBuilder.Entity<OrderCustomized>()
            .Map(m =>
            {
                m.Properties(o => new { o.OrderID, o.OrderDate, o.CustomerID, o.EmployeeID });
                m.ToTable("Order");
            })
            .Map(m =>
            {
                m.Properties(c => new { c.CustomerID, c.CustomerContactName, c.CustomerPhone });
                m.ToTable("Customer");
            })
            .Map(m =>
            {
                m.Properties(e => new { e.EmployeeID, e.EmployeeLastName, e.EmployeeFirstName });
                m.ToTable("Employee");
            })
            ;

        base.OnModelCreating(modelBuilder);
    }

    public virtual DbSet<Category> Categories { get; set; }
    public virtual DbSet<Contact> Contacts { get; set; }
    public virtual DbSet<CustomerDemographic> CustomerDemographics { get; set; }
    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<Employee> Employees { get; set; }
    public virtual DbSet<Order_Detail> Order_Details { get; set; }
    public virtual DbSet<Order> Orders { get; set; }
    public virtual DbSet<Product> Products { get; set; }
    public virtual DbSet<Region> Regions { get; set; }
    public virtual DbSet<Shipper> Shippers { get; set; }
    public virtual DbSet<Supplier> Suppliers { get; set; }
    public virtual DbSet<Territory> Territories { get; set; }

    public virtual DbSet<OrderCustomized> OrdersCustomized { get; set; }
}

我一直收到错误&#34;实体类型OrderCustomized不是当前上下文模型的一部分。&#34;

如何为当前上下文创建OrderCustomized模型的一部分?

我非常感谢任何示例代码,因为我在搜索互联网时找不到任何代码。

谢谢, 凯利

1 个答案:

答案 0 :(得分:0)

请记住更新T4文件(.tt扩展名)。让我知道在那次行动之后它是否有效。