简体   繁体   English

EF代码的第一个外键被忽略,得到“无效的列名”

[英]EF code first foreign key ignored, getting “Invalid column name”

I have a fairly simple class which holds potential types of users: 我有一个非常简单的类,其中包含潜在的用户类型:

public class Core_UserType
{
    [Key]
    public long ID { get; set; }
    [Required]
    public String Name { get; set; }    
    [ForeignKey("TrackingInfo")]
    public long ObjectID { get; set; }

    public virtual Core_TrackingInfo TrackingInfo { get; set; }
}

I have excluded some of the code for brevity, but the key property is TrackingInfo . 为了简洁起见,我已经排除了一些代码,但是关键属性是TrackingInfo This entity (and the entire code first entity model are in a class library called EntityModel. 该实体(以及整个代码优先实体模型)都在称为EntityModel的类库中。

The solution has 2 web application projects (both ASP.Net MVC), both of which reference this class library. 该解决方案有2个Web应用程序项目(均为ASP.Net MVC),这两个项目均引用此类库。

In the library itself there is some code that inserts a few entries, one of which is a new Core_UserType . 在库本身中,有一些代码可以插入一些条目,其中之一是新的Core_UserType When called from application A this runs perfectly. 当从应用程序A调用时,它可以完美运行。 The problem is when called from project B, the code fails (after inserting some other objects OK) with: 问题是从项目B调用时,代码失败(在插入其他一些对象之后):

An error occurred while saving entities that do not expose foreign key properties for their relationships. 保存不公开外键属性为其关系的实体时发生错误。 The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. EntityEntries属性将返回null,因为无法将单个实体标识为异常的来源。 Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. 通过在实体类型中公开外键属性,可以简化保存时的异常处理。 See the InnerException for details. 有关详细信息,请参见InnerException。

And an inner exception: 还有一个内部异常:

Invalid column name TrackingInfo_ID 无效的列名TrackingInfo_ID

I dug a little deeper into the stack track and found that project B is trying to execute this SQL: 我对堆栈轨道进行了更深入的研究,发现项目B正在尝试执行此SQL:

INSERT [dbo].[Core_UserType]([Name], [ObjectID], [TrackingInfo_ID])
VALUES (@0, @1, @2)
SELECT [ID]
FROM [dbo].[Core_UserType]
WHERE @@ROWCOUNT > 0 AND [ID] = scope_identity()

Obviously TrackingInfo_ID doesn't exist (it should be using ObjectID ) so it fails. 显然TrackingInfo_ID不存在(应该使用ObjectID ),所以它失败了。

The question is why is project A able to honour the ForeignKey attribute and project B isn't? 问题是为什么项目A能够使用ForeignKey属性,而项目B却不能呢?

You could try to do this the opposite way: This means the ForeignKey DataAnnotaion on the other property: 您可以尝试以相反的方式执行此操作:这意味着另一个属性上的ForeignKey DataAnnotaion:

public long ObjectID { get; set; }

[ForeignKey("ObjectID")]
public virtual Core_TrackingInfo TrackingInfo { get; set; }

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM