Reputation: 285
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.
Upvotes: 0
Views: 2585
Reputation: 1
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.
Upvotes: 0
Reputation: 177133
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).
Upvotes: 6
Reputation: 1117
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;
Upvotes: 1