我有以下型号:
public class Customer
{
[Key]
[ForeignKey("MainAddress")]
[Column(Order = 1)]
public string CustomerNumber { get; set; }
// .. some more standard props that aren't keys/FKs etc
[ForeignKey("MainAddress")]
[Column(Order = 2)]
public string MainAddressCode { get; set; }
[Include]
[Association("Addresses", "CustomerNumber", "CustomerNumber")]
public IList<CustomerAddress> Addresses { get; set; }
[Include]
[Association("MainAddress", "CustomerNumber,MainAddressCode", "CustomerNumber,CustomerAddressCode")]
public CustomerAddress MainAddress { get; set; }
}
public class CustomerAddress
{
public string CustomerNumber { get; set; }
public string CustomerAddressCode { get; set; }
// .. address props after this
}
我希望能够获取实体框架来检索客户的地址列表,还可以使用MainAddressCode
字段结合CustomerNumber
来检索主地址
目前我能得到的最接近的是生成的查询如下所示:
SELECT
1 AS [C1],
[Extent1].[CustomerNumber] AS [CustomerNumber],
[Extent1].[CustomerName] AS [CustomerName],
[Extent1].[MainAddressCode] AS [MainAddressCode],
[Extent2].[CustomerNumber] AS [CustomerNumber1],
[Extent2].[CustomerAddressCode] AS [CustomerAddressCode],
[Extent2].[Customers_CustomerNumber] AS [Customer_CustomerNumber] <--- Argh!
FROM [dbo].[Customers] AS [Extent1]
LEFT OUTER JOIN [dbo].[CustomerAddress] AS [Extent2] ON ([Extent1].[MainAddressCode] = [Extent2].[CustomerAddressCode]) AND ([Extent1].[CustomerNumber] = [Extent2].[CustomerNumber])
我认为这是因为EF按照惯例为Customer
表格的FK前面的CustomerAddress
实体名称添加前缀。
如何在CustomerAddress
表上指定外键的列名,以便查询正确执行?我是否需要使用流畅的API而不是属性?
答案 0 :(得分:0)
结束了这个:
var config = modelBuilder.Entity<Customer>();
config.HasMany(x => x.Addresses)
.WithRequired()
.HasForeignKey(x => new { x.CustomerNumber });
config.HasRequired(x => x.MainAddress)
.WithMany()
.HasForeignKey(x => new { x.CustomerNumber, x.MainAddressCode });
到目前为止似乎工作!