为什么EF产生无效列时,我有相同的列名作为子表中的外键
本文关键字:EF 无效 为什么 | 更新日期: 2023-09-27 18:09:26
我得到了这2个模型,我使用"include"来获取所有相关实体,我的LINQ是这样的,当我执行它时会抱怨——Invalid column Cust_ProfileTbl_bintAccountNo
LINQ
DB context = new DB();
List<Cust_ProfileTbl> profile = context.profile.ToList();
var r = from ord in context.profile.Include("balance")
select ord;
public class Cust_ProfileTbl
{
[Key]
public long bintAccountNo { get; set; }
public virtual BP_BalanceTbl balance { get; set; }
}
public class BP_BalanceTbl
{
[Key]
public long bintAccountNo { get; set; }
}
生成的SQL
SELECT
[Project1].[bintAccountNo] AS [bintAccountNo],
[Project1].[Cust_ProfileTbl_bintAccountNo] AS [Cust_ProfileTbl_bintAccountNo]-- Invalid column
FROM (
SELECT
[Extent1].[bintAccountNo] AS [bintAccountNo],
[Extent2].[Cust_ProfileTbl_bintAccountNo] AS [Cust_ProfileTbl_bintAccountNo],
CASE WHEN ([Extent2].[intPartner] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM [dbo].[Cust_ProfileTbl] AS [Extent1]
LEFT OUTER JOIN [dbo].[BP_BalanceTbl] AS [Extent2] ON [Extent1].[bintAccountNo] = [Extent2].[Cust_ProfileTbl_bintAccountNo]
) AS [Project1]
ORDER BY [Project1].[bintAccountNo] ASC, [Project1].[C1] ASC
我试图摆脱这个bug
- 在BP_BalanceTbl中添加1个身份PK列,(我不喜欢这样做)
- 更改为使用Join方法。(但我想知道为什么这种情况发生不只是逃避错误,以及如何避免这种情况?)
应OP的要求,我将发表我的评论作为答案:
所以这个问题是基于一个模型属性被分配主键和外键的事实。要告诉EF创建这个,你需要在属性上使用DataAnnotations:
[Key, ForeignKey("Cust_ProfileTbl")]
public long bintAccountNo { get; set; }
,你可能还需要引用相关实体作为虚拟属性:
public virtual Cust_ProfileTbl{get; set;}