简体   繁体   中英

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
            }
        }

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.

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