Reputation: 10514
On my MVC4 application I have a page where an user can be placed in a schedule. The idea is that you can select a person and that they will be entered on the schedule. The Schedule Model looks as follows:
public class Schedule {
[Key]
public int scheduleId { get; set; }
[Column(TypeName = "Date")]
[DataType(DataType.Date)]
public DateTime date { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}
The User Model where the Schedule Model refers to looks like this:
public class User {
public int UserId { get; set; }
[Display(Name = "Naam")]
public string Name { get; set; }
public string Email { get; set; }
[Display(Name = "Beschikbaar")]
public bool isAvailable { get; set; }
}
An user can be placed on the scheduling page with the following controller:
public ActionResult Create(Schedule schedule)
{
if (ModelState.IsValid)
{
db.Schedules.Add(schedule);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(schedule);
}
The Schedule/Create view looks like this:
and has the following code:
<h2>Schedule a person</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Schedule</legend>
<div class="editor-label">
@Html.LabelFor(model => model.UserId)
</div>
<div class="editor-field">
@Html.DropDownList("UserId", String.Empty)
@Html.ValidationMessageFor(model => model.UserId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.date)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.date)
@Html.ValidationMessageFor(model => model.date)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.User.isAvailable)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.User.isAvailable)
@Html.ValidationMessageFor(model => model.User.isAvailable)
</div>
<p>
<input type="submit" value="Plan" />
</p>
</fieldset>
}
This code does place the user on the schedule on the specified date. But somehow an extra "null" user is created in the database every time an existing user is added to the schedule. See this image:
I have been breaking my head over this unwanted behaviour for the past hours. The Create action of the ScheduleController does not specify to create an extra user. I have no idea why it does do so anyway.
Does anyone here have any idea?
Upvotes: 0
Views: 35
Reputation: 151720
It's because of your .User.IsAvailabe property. This creates a new user when adding the schedule.
You'll have to attach the existing user to your schedule. Perhaps you can even get rid of UserId and use User.Id in your form.
Upvotes: 1