Error saving entity framework

0

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?

    
asked by anonymous 20.04.2017 / 00:29

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

Yes, you may not be using context to observe User before.

  

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

This does not exist, "add by my virtual property". If the Entity Framework understands that your objects do not yet exist, it will insert them as if they were new.

Its Add function can be considered an anti-default. There is no verification of associated entities before the addition. The right thing 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 log.

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();
    
20.04.2017 / 00:37