C# - Foreign key references invalid table - Basic Migration not working

僤鯓⒐⒋嵵緔 提交于 2019-12-04 13:02:45

First I recommend you to change the FK name that you are using in the ForeignKey attributes for the navigation property names:

public class UserLoc
{
    [Key]
    public int ul_id { get; set; }

    [ForeignKey("user")]
    public int fk_user_id { get; set; }
    public virtual User user { get; set; }

    [ForeignKey("location")]
    public int fk_location_id { get; set; }
    public virtual Locations location { get; set; }
}

This way you are telling it which navigation property represents the relationship it is a foreign key for.

After that, remove the old migration and try to run again Add-Migration command to regenerate it. You should see now that CreateIndex method is called before AddForeignKey method:

CreateIndex("dbo.UserLoc", "fk_user_id");
AddForeignKey("dbo.UserLoc", "fk_user_id", "dbo.Users", "user_id");

CreateIndex("dbo.UserLoc", "fk_loc_id");
AddForeignKey("dbo.UserLoc", "fk_loc_id", "dbo.Locations", "loc_id");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!