I have a very basic problem, but I must be short of coffee to understand what is happening.
I have an entity like this:
public class Client : BaseEntity<Client>
{
[Required]
public string CorporateName { get; set; }
// Várias outras propriedades que eu tirei pra não ficar muita coisa
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
public Client()
{
this.User = new User();
}
}
So far, I do not see any apparent problems. However, my BaseEntity does Create this way (I've created generic methods so all my entities work the same way and I do not have to replicate the same code multiple times):
public static void Add(params T[] items)
{
using (var context = new DBContext())
{
try
{
foreach (T item in items)
context.Entry(item).State = EntityState.Added;
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
}
When I try to add a Client, Add throws an error saying that the User property has the Name field that is required. However, I'm setting the UserID instead of the User (for a very good reason: setting the User and doing the Add, it doubled the User's registry).
How do I make EntityFramework not try to add by my virtual property and add only by FK?