Etrit
Etrit

Reputation: 895

Invalid column name "User_Id"

I'm getting this exception about a column "User_Id" which I don't have anywhere in my database or in my code. It just showed up like that... What is the problem ? Any suggestions ? I get this exception when I want to add something.

        protected override void BaseAdd(Meal entity)
        {
            using (var context = new ProjectContext())
            {
                context.Meals.Add(entity);
                context.SaveChanges(); //here is where I get the exception
            }
        }

Upvotes: 2

Views: 5747

Answers (1)

Stan
Stan

Reputation: 26511

You have User_Id because you mapped that User can have multiple Meals in your POCO like so.

public class User
{
    public int Id { get; set; }
    public int Name { get; set; }

    public ICollection<Meal> Meals { get; set; }
}

Because of that EF automatically assumes that Meal will have 1-many relations with User.

I suggest you first do update-database -v -f to make sure your database is set up properly. And second - I strongly advise making relational-ids also in your POCO so your database is 1-1 with your POCO and you won't get any surprises like these.

Upvotes: 5

Related Questions