sql server - The INSERT statement conflicted with the FOREIGN KEY. Entity includes ForeignKey Id property -
i'm doing 1 many relationship database entity framework id property.
i have 2 model classes:
public class personmodel { [key] public int personid { get; set; } public string nickname { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string email { get; set; } public int teamrefid { get; set; } [foreignkey("teamrefid")] public virtual teammodel teammodel { get; set; } } public class teammodel { public teammodel() { teammembers = new list<personmodel>(); this.tournaments = new hashset<tournamentmodel>(); } [key] public int teamid { get; set; } public string teamname { get; set; } public virtual icollection<personmodel> teammembers { get; set; } public virtual icollection<tournamentmodel> tournaments { get; set; } public virtual matchupentrymodel matchupentry { get; set; } public virtual matchupmodel matchup { get; set; } } when i'm trying create new person entity, error:
sqlexception: insert statement conflicted foreign key constraint "fk_dbo.personmodel_dbo.teammodel_teamrefid". conflict occurred in database "tournament2", table "dbo.teammodel", column 'teamid'.
making foreign key in person model nullable should solve problem note created person have no team until modify later after create team
public class personmodel { [key] public int personid { get; set; } public string nickname { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string email { get; set; } public int? teamrefid { get; set; } [foreignkey("teamrefid")] public virtual teammodel teammodel { get; set; } }
Comments
Post a Comment