我试图将来自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; }
}
}
最佳答案
尝试在您的OnModelCreating
类的context
事件上添加以下代码:
modelBuilder.Entity<ApplicationUser>()
.HasOptional<Contractor>(user => user.Contractor)
.WithRequired(cont => cont.ApplicationUser)
.WillCascadeOnDelete(true);
这用于
ApplicationUser
和Contractor
之间的“一对一关系”(其中ApplicationUser
不需要Contractor
)。如果希望每个用户都需要
Contractor
,只需将HasOptional
更改为HasRequired
。关于sql-server - 外键 Entity Framework 6在相关表中插入了null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30266975/