0
I have a very basic problem, but I must be short of coffee to understand what is happening.
I have such an entity:
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 don’t see any apparent problem. However, my Baseentity does Create this way (I created generic methods so that all my entities work the same way and I don’t have to replicate the same code several 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 am setting the Userid and not the User (for a very noble reason: setting the User and doing the Add, it duplicated the User record).
How do I make Entityframework not try to add by my virtual property and add only by FK?
But that way, I would have to create CRUD for each entity, right? I did it this other way to make it easier and reuse the code. It is possible, somehow, to leave the "generic" CRUD to all my entities without having problems with these relations?
– Claudio Neto
Define "Generic CRUD". You have a client you want to relate to the user. The relationship between
Cliente
andUser
is done in Controller. The code will be reused where?– Leonel Sanches da Silva
Same Baseentity for all entities already with CRUD implemented. The relationship between Client and User, yes, is done in the Controller, however, for me not to have to implement Create in Client, User and all other entities, I created (based on links I found on the Internet) this Baseentity that does it for all. But it’s not working.
– Claudio Neto
In fact it won’t work. You can’t do what you want with just this code. For each foreign key, you need to attach an entity to the context and only then enter the new record.
– Leonel Sanches da Silva