【发布时间】:2013-11-29 15:28:38
【问题描述】:
我是 EF Code First 的新手,并且已经享受了好几个星期了。我面临处理 2 个数据库(都在同一个 Sqlserver 中)。第一个数据库包含一个表,我只需为其主键引用它,它与我创建的表(第二个 DbContext - 第二个数据库)“逻辑上”相关。基于此键,我将查询我的第二个 DbContext 表(mvc 站点的实际相关表)。顺便说一句,Customer 有 0..* CustomerUsers。
第一个数据库上下文:
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; }
}
OnModel创建方法:
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 服务器资源管理器中)。
这种设计会遇到任何与部署相关的问题吗?
【问题讨论】:
标签: asp.net-mvc entity-framework