c# - Entity Framework 'column does not allow nulls' -
yet again amazing entity framework has failed make simple, simple... have created basic set of models, company, county, user's have m:1 relationship company. have table created called companyusers believe generate table design like.
however cannot enter basic user database claiming cannot have null userid though setting id.
i understand table design weird, may want switch m:m relationship , having table setup nice that. secondly, having data in 3 tables makes writing sql queries easier because of joins.
exact error:
system.data.sqlclient.sqlexception: cannot insert value null column 'userid', table 'ssi.database.context.software.dbo.users'; column not allow nulls. insert fails.
seed:
var _company = new company() { companyid=1, name="company inc." }; var _counties = new list<county>() { new county(){ name="place1" }, new county(){ name="place2"} }; context.companies.addorupdate(_company); var _user = new user() {userid=1, companyid=_company.companyid, company=_company, name = "john smith" }; if (context.counties.count() == 0) { context.counties.addrange(_counties); } context.users.addorupdate(_user);
all models:
company:
public class company { public company() { users = new list<user>(); } [key] public int companyid { get; set; } public string name { get; set; } public icollection<user> users { get; set; } }
user:
public class user { [key] [databasegenerated(databasegeneratedoption.identity)] public int userid { get; set; } public string name { get; set; } public nullable<int> companyid { get; set; } [foreignkey("companyid")] public company company { get; set; } }
companyuser table:
public class companyusers { [key] [column(order = 1)] public int companyid { get; set; } [foreignkey("companyid")] public virtual company company { get; set; } [key] [column(order = 2)] public int userid { get; set; } [foreignkey("userid")] public virtual user user{ get; set; } }
Comments
Post a Comment