Error saving Entity framework

Asked

Viewed 287 times

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?

1 answer

1

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).

Yes, possibly you are not using the context to observe the User before.

How do I make Entity Framework not try to add by my virtual property and add only by FK?

There’s no such thing as "add to my virtual property". If the Entity Framework understands that its objects do not yet exist, it will insert as if they were new.

Its function Add can be considered an anti-standard. There is no verification of the associated entities before the addition. Right would be something like this:

var user = db.Users.FirstOrDefault(u => u.UserID == 1);
var client = new Client { User = user };
db.Clients.Add(client);
db.SaveChanges();

Selecting a user will make the context observe the record.

Now, if neither exists, the path is:

var user = new User { Name = "Fulano" };
var client = new Client { User = user };
db.Clients.Add(client);
db.SaveChanges();
  • 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?

  • Define "Generic CRUD". You have a client you want to relate to the user. The relationship between Cliente and User is done in Controller. The code will be reused where?

  • 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.

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.