简体   繁体   中英

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 . This entity (and the entire code first entity model are in a class library called EntityModel.

The solution has 2 web application projects (both ASP.Net MVC), both of which reference this class library.

In the library itself there is some code that inserts a few entries, one of which is a new Core_UserType . When called from application A this runs perfectly. The problem is when called from project B, the code fails (after inserting some other objects OK) with:

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. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

And an inner exception:

Invalid column name TrackingInfo_ID

I dug a little deeper into the stack track and found that project B is trying to execute this 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.

The question is why is project A able to honour the ForeignKey attribute and project B isn't?

You could try to do this the opposite way: This means the ForeignKey DataAnnotaion on the other property:

public long ObjectID { get; set; }

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

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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