I'm trying to have this setup in my asp.net mvc app:
- I'm using
AspNetUser
to handle users. - One user can have many cars
- One car can have many repairs
Car model
public class Car
{
[Key]
public int CarID { get; set; }
[Required]
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<Maintenance> Maintenances { get; set; }
[Required]
public string Brand { get; set; }
// a bunch of other string properties related to a car...
}
Maintenance model
public class Maintenance
{
public int CarID { get; set; }
[Key]
public int MaintenanceID { get; set; }
public int Mileage { get; set; }
public DateTime EntryDate { get; set; }
public DateTime ExitDate { get; set; }
public decimal Cost { get; set; }
public virtual Car Automobile { get; }
}
IdentityModels.cs
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Car> Cars { get; set; }
// ...
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Car>()
.HasRequired(c => c.ApplicationUser)
.WithMany(t => t.Cars)
.Map(m => m.MapKey("OwnerID"));
}
public DbSet<Car> Cars { get; set; }
public DbSet<Maintenance> Maintenances { get; set; }
}
I took a look at table definitions, they seems to be OK (OwnerID
foreign key is correctly setup), but for some reason this doesn't work when I try to add a new car:
public ActionResult Create(Car car)
{
if (ModelState.IsValid)
{
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
- ModelState.IsValid is always false
car.ApplicationUser
is alwaysnull
I'm new to asp.net mvc, can someone please tell me what I'm doing wrong here?