Здравствуйте, помогите, пожалуйста, понять, что не так с моим кодом добавления данных в базу? Мои модели для того, чтобы можно было отображать и вводить данные сразу по двум моделям создала специальный класс.
public class Owner
{
[Key]
public int OwnerID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime Birthday { get; set; }
public int Experience { get; set; }
public virtual ICollection<Car> Cars { get; set; }
}
public class Car
{
[Key]
public int CarID { get; set; }
public string Model { get; set; }
public string Mark { get; set; }
public string Type { get; set; }
public int Price { get; set; }
public string YearofRelease { get; set; }
public virtual ICollection<Owner> Owners { get; set; }
}
public class CarOwner
{
public int CarOwnerID { get; set; }
public Owner Owner { get; set; }
public Car Car { get; set; }
}
Вот мой код для метода добавления, что здесь не так?
public ActionResult Create(CarOwner owner)
{
if (ModelState.IsValid)
{
db.Owners.Add(owner.Owner);
owner.Owner.Cars.Add(owner.Car);
db.Cars.Add(owner.Car);
db.CarOwners.Add(owner);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
An exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll but was not handled in user code."Value cannot be null.\r\nParameter name: entity"
Вот отображение странички
@model CarOwner_2.Models.CarOwner
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Owner</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Owner.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Owner.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Owner.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Owner.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Owner.Surname, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Owner.Surname, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Owner.Birthday, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Owner.Birthday, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Owner.Birthday, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Owner.Experience, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Owner.Experience, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Owner.Experience, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Car.Model, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Car.Model, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Car.Model, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Инициализация базы данных
public class CarOwnerInit : DropCreateDatabaseIfModelChanges<CarOwnersContext>
{
protected override void Seed(CarOwnersContext context)
{
Owner ow1 = new Owner { Name = "Sam", OwnerID = 1, Surname = "Lucky", Birthday = DateTime.Parse("1993-06-21"), Experience = 3 };
Owner ow2 = new Owner { Name = "Nick", Surname = "May", Birthday = DateTime.Parse("1994-04-06"), Experience = 5 };
context.Owners.Add(ow1);
context.Owners.Add(ow2);
context.SaveChanges();
Car ca1 = new Car { Model = "Alfa 146", CarID = 2, Mark = "Alfa", Type = "passenger", Price = 7, YearofRelease = "2001", Owners = new List<Owner>() { ow1, ow2 } };
Car ca2 = new Car { Model = "Bentley 126", CarID = 4, Mark = "Bentley", Type = "passenger", Price = 77, YearofRelease = "2011", Owners = new List<Owner>() { ow2 } };
context.Cars.Add(ca1);
context.Cars.Add(ca2);
context.SaveChanges();
base.Seed(context);
}
}
Сама база данных
public class CarOwnersContext : DbContext
{
public CarOwnersContext()
: base("DefaultConnection")
{
}
public DbSet<Owner> Owners { get; set; }
public DbSet<CarOwner> CarOwners { get; set; }
public DbSet<Car> Cars { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
car = owner.Car;
? Вы же теряете ссылку на только что созданный объектValue cannot be NULL?
@
перед именем пользователя. я имел ввиду что свойствоOwners
классаCar
у Вас скорее всегоnull
отсюда и исключение при попытке добавить объект в коллекцию