多个DbContexts不同的数据库

时间:2013-11-29 03:35:23

标签: asp.net-mvc entity-framework

我是EF Code First的新手,现在已经好几个星期了。我面临处理2个数据库(都在同一个Sqlserver中)。第一个数据库包含1个表,我只需要引用它的主键,它与我创建的表“逻辑”相关(第二个DbContext - 第二个数据库)。基于此密钥,我将查询我的第二个DbContext表(mvc站点的实际相关表)。顺便说一句,客户有0 .. * CustomerUsers。

第一个dbcontext:

public class Customer
{

    [StringLength(10, MinimumLength = 3), Required]
    public string CompanyID { get; set; }

    [StringLength(8, MinimumLength = 3)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string CustomerID { get; set; }


    [StringLength(500)]
    public string CustomerName { get; set; }


    //*Initially, under the same dbContext, they were related, but now am separating
    //them because of physical database separation; hence the navigation property   
    //public virtual ICollection<CustomerUser> CustomerUsers { get; set; }

}

在OnModelCreating方法中:

modelBuilder.Entity<Customer>()
            .HasKey(c => new { c.CompanyID, c.CustomerID});

'逻辑'相关实体

public class CustomerUser
{

    [Display(Name = "Customer ID")]
    public int CustomerUserID { get; set; }

    //[ForeignKey("Customer")]
    [Display(Name = "CompanyID"), Required]
    [StringLength(10, MinimumLength = 3)]
    public string CompanyID { get; set; }

    //[ForeignKey("Customer")]
    [Display(Name = "CustomerID"), Required]
    [StringLength(8, MinimumLength = 3)]
    public string CustomerID { get; set; }


    [StringLength(50), Display(Name = "First Name"), Required]
    public string FirstName { get; set; }

    [StringLength(50), Display(Name = "Last Name"), Required]
    public string LastName { get; set; }

    //*Initially related thru foreign key to Customer but separation of database
    //thus no more relations – just a querying of Customer’s id from other database
    //public virtual Customer Customer { get; set; }


}

OnModelCreating方法:

modelBuilder.Entity<CustomerUser>()
            .HasKey(c => new { c.CustomerUserID });

        modelBuilder.Entity<CustomerUser>()
            .HasRequired(p => p.Customer)
            .WithMany(c => c.CustomerUsers)
            .HasForeignKey(p => new {p.CompanyID, p.CustomerID});

我如何以及在何处声明我的DbContexts?目前我有一个由Web应用程序引用的程序集。此外,如何为我的部署做好准备?用于仅引用其密钥的一个表已经存在,而其余的表,我还没有在SqlServer中创建(它们存在于我的VS2012服务器资源管理器中)。

我可能会遇到与此设计相关的任何与部署相关的问题吗?

1 个答案:

答案 0 :(得分:0)

  

我如何以及在何处声明我的DbContexts?

大问题。数据访问层是典型的。不在核心/域层中。将核心与EF结合起来。

  

目前我有一个由Web应用程序引用的程序集。也,   这对我的部署有什么影响?

如果你不使用CORE / DOMAIN Layer +数据访问Layer + UI Layer,那么开发将与数据访问工具紧密结合。

  

用于仅引用其密钥的一个表已经存在,   而其他表格,我还没有创建   SqlServer(它们存在于我的VS2012服务器资源管理器中)。会的吗?   是否可能与此设计相关的任何与部署相关的问题?

不,从一个解决方案多个上下文多个数据库访问对EF来说不是问题。 虽然您需要谨慎管理实例化上下文的方式。 例如https://stackoverflow.com/a/20118259/1347784

相关问题