外键实体框架6在依赖表中插入null

时间:2015-05-15 19:04:40

标签: sql-server asp.net-mvc entity-framework

我尝试使用AspNetUsers的主键ID作为我的Contractor表,它给我一个错误说"无法将NULL值插入列ID"。当我在注册用户后尝试创建承包商并且它们出现在AspNetUsers中时,会发生错误。

  public class Contractor
{
    [Key, ForeignKey("ApplicationUser")]
    public string ID { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; } 



 public class ApplicationUser : IdentityUser
{

    public virtual Contractor Contractor { get; set; }

修改

承包商是音乐家的基类。 从控制器创建音乐家的代码

     public ActionResult Create([Bind(Include = "FirstName,LastName,ZipCode,Phone,PrimaryInstrument,PrimaryGenre,NextDateAvailable,WebsiteLink, YouTubeLink,SoundCloudLink, ReverbNationLink,YearsOfExperience,Description")] Musician musician, HttpPostedFileBase image)
    {
        if (ModelState.IsValid)
        {
            if (image != null)
            {
                string imageFilePath = Server.MapPath("~/Images/");
                image.SaveAs(imageFilePath + image.FileName);

                musician.ImageData = new byte[image.ContentLength];
                musician.ImageMimeType = image.ContentType;
                musician.ImageName = image.FileName;

            }


            musician.CreateDate = DateTime.Now;

            db.Musicians.Add(musician);
            db.SaveChanges();
            return View();
        }

        return View(musician);
    }

音乐家班:

  public class Musician : Contractor
{
    public string PrimaryInstrument { get; set; }
    public string PrimaryGenre { get; set; }
    public string WebsiteLink { get; set; }
    public string YouTubeLink { get; set; }
    public string SoundCloudLink { get; set; }
    public string  ReverbNationLink { get; set; }
}

}

2 个答案:

答案 0 :(得分:2)

尝试在OnModelCreating课程的context事件中添加此代码:

modelBuilder.Entity<ApplicationUser>()
    .HasOptional<Contractor>(user => user.Contractor)
    .WithRequired(cont => cont.ApplicationUser)
    .WillCascadeOnDelete(true);

这是为了一对一的关系&#34;在ApplicationUserContractor之间(ApplicationUser 需要Contractor)。

如果您希望每个用户Contractor ,只需更改HasOptional的{​​{1}}。

答案 1 :(得分:0)

我意识到我可以将User.Identity.GetUserId()用于Id值,并将其保存到我的数据库模型中。它解决了外键问题。

相关问题