简体   繁体   中英

EF 4.1 code first Invalid column name “User_UserId”

I can't figure out why this is causing EF error: Invalid column name 'User_UserId' when saving in EF.

Here is my model:

 [DataContract(IsReference = true)]
public class User
{
    [Key]
    [DataMember]
    public virtual Guid UserId { get; set; }

    [DataMember]
    public virtual string Username { get; set; }

    [DataMember]
    public virtual string Password { get; set; }

    [DataMember]
    public virtual string Email { get; set; }

    [DataMember]
    public virtual ICollection<FriendList> FriendLists { get; set; }
}

[DataContract(IsReference = true)]
public class FriendList
{
    [Key]
    [DataMember]
    public virtual Guid FriendListId { get; set; }

    [DataMember]
    [ForeignKey("User")]
    public virtual Guid UserId { get; set; }

    [DataMember]
    public virtual User User { get; set; }

    [DataMember]
    [ForeignKey("FriendUser")]
    public virtual Guid FriendUserId { get; set; }

    [DataMember]
    public virtual User FriendUser { get; set; }
}

basically, its one to many relationship with users having a friendlists.

You have two navigation properties of type User in your FriendList class. EF cannot figure out which of these belong to User.FriendLists and then creates for all three navigation properties a separate one-to-many relationship, one of them has the default foreign key name User_UserId .

You can overwrite this convention with the InverseProperty attribute:

public class FriendList
{
    // ...

    [DataMember]
    [InverseProperty("FriendLists")]
    public virtual User User { get; set; }

    // ...
}

Now, User.FriendLists and FriendList.User are the endpoints of the same one-to-many relationship and FriendList.FriendUser defines a second one-to-many relationship (but without an endpoint in the User class).

I guess:

1) The attribute ForeignKey in your case must be set as [ForeignKey("UserId")] and not as [ForeignKey("User")]

2) Or If one of these classes are not mapped you must set the attribute [NotMapped] on it;

Your ForeignKey attribute is in the wrong place.

Try this:

[DataMember]
public virtual Guid UserId { get; set; }

[DataMember]
[ForeignKey("UserId")]
public virtual User User { get; set; }

[DataMember]
public virtual Guid FriendUserId { get; set; }

[DataMember]
[ForeignKey("FriendUserId")]
public virtual User FriendUser { get; set; }

At least it worked for me.

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