Entity Framework 6 external framework gets null in dependent table
I am trying to use Primary Key Id from AspNetUsers for my Contractor table and it gives me the error "Cannot insert NULL value into Column Id". The error occurs when I try to create a Contractor after user registration and they appear in 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; }
EDIT
The Contractor is the base class for the musician. Code for creating a musician from a controller
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);
}
Musician class:
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; }
}
}
source to share
Try adding this code to OnModelCreating
your class event context
:
modelBuilder.Entity<ApplicationUser>()
.HasOptional<Contractor>(user => user.Contractor)
.WithRequired(cont => cont.ApplicationUser)
.WillCascadeOnDelete(true);
This is for a one-to-one relationship between ApplicationUser
and Contractor
(with ApplicationUser
not requiring Contractor
).
If you want it to Contractor
be required for every user, just change HasOptional
to HasRequired
.
source to share