Reputation: 55
I have the following model:
[Table("EventUserDetails")]
public class EventUserDetail
{
[Key]
public int Id { get; set; }
public bool Invited { get; set; }
public DateTime? InviteDate { get; set; }
[Required]
public virtual User User { get; set; }
[Required]
public virtual Event Event { get; set; }
}
Event and User are also models and I have them set as [Required] because I wanted the db fields to be not nullable (code first).
If I get an object from the database and try to save it:
EventUserDetail de = db.EventUserDetails.Where(m => m.Id == id).Single();
de.Invited = true;
db.SaveChanges();
I get errors:
- Property: "User", Error: "The User field is required."
- Property: "Event", Error: "The Event field is required."
User and Event properties represent other linked objects, and during the debugging, right before saving, I can see that they are populated.
Why am I getting these errors? Is having [Required] for virtual properties that represent other models not recommended?
Upvotes: 2
Views: 1057
Reputation: 27861
You can include the foreign keys in your model and specify that the foreign keys themselves are required like this:
public class EventUserDetail
{
[Key]
public int Id { get; set; }
public bool Invited { get; set; }
public DateTime? InviteDate { get; set; }
[Required]
[ForeignKey("User")]
public int UserId { get; set; }
public virtual User User { get; set; }
[Required]
[ForeignKey("Event")]
public int EventId { get; set; }
public virtual Event Event { get; set; }
}
This will allow you to update the model without loading the related entities. EF will force the required requirement by making sure that the foreign keys UserId
and EventId
have been set.
Please note that you might want to change the names of these properties in the model to match the ones in the database so that the model would match the table structure in the database.
Upvotes: 3