none
Ef Code First try insert an existe entity if there isn't scalar property for foreign keys RRS feed

  • Question

  • Hi, guys.

    I would like to know why this problems, see this toy sample.

    public class City 
        { 
            public virtual int IdCity { getset; }
            public virtual State State { getset; }
     
            public virtual string Name{ getset; }
        }

    and

    public class State {
            public virtual int IdState { getset; }
            public virtual string Name { getset; }
            public virtual string Acronym { getset; }
     
            public virtual IList<City> Cities { getset; }
        }

    See, City doesn't have an scalar property for State, like "IdState", I will use Map to define foreignkey.

    public class CityMap : EntityTypeConfiguration<City> {
            
            public CityMap() 
            {
    	    ToTable("City");
                HasKey(x => x.IdCity);
                HasRequired(x => x.State).WithMany().Map(m=>m.MapKey("IdState"));
            }
        }

    and StateMap

    public class StateMap : EntityTypeConfiguration<State> {
            
            public StateMap()
            {
    	    ToTable("State");
    	    HasKey(x => x.IdState);
                HasMany(x => x.Cities);
            }
        }
    

    Now, I want to inser a new City using an existing state.

      using (EFContext contex=new EFContext())
                {
                    City newCity=new City();
                    newCity.Name = "My new City";
                    newCity.State = new State() { IdState = 443 };//only sample 
                    contex.Cities.Add(cidadeNova);
                    contex.SaveChanges();
                }

    This is an simple sample but unfortunatelly EF try update State entity. I think that if we have to create an primary key to entities, EF should control this.

    Ok, someone know how solve this problem?

    First: I know that I should use scalar property for foreign keys;

    Second: I want to use an unattached object(context), because I don't care obout this.

    There is some problems with my mapping?

    help me please.

     

    Thanks.

     

     



    Tuesday, September 20, 2011 7:10 PM

All replies

  • Hello,

    Thank you for posting.

    Did you receive any error information from your code snippets? If yes, could you please provide more detailed information to us to analyze your question?

    In addition, we also recommand you can send the demo application to us to help us reproduce your question more convenient. My mail: v-xugong@microsoft.com

    Thanks,


    Larcolais Gong[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, September 22, 2011 4:04 AM
  • Hello, Larcolais.

     

    Thanks for your reply.

    The main problem is that, some times, I have a lot of problems with EF 4.1.For example, how to define the cascade of updates ? How can I define this scope?

    I did this code to solve this problem:

            public override int SaveChanges()
            {
                var contextAdapter = this as IObjectContextAdapter;
     
                var entries = this.ChangeTracker.Entries().ToList();
     
                foreach (var dbEntityEntry in entries)
                {
                    ObjectStateEntry entry = null;
     
                    if (contextAdapter.ObjectContext.ObjectStateManager.TryGetObjectStateEntry(dbEntityEntry.Entity,
                                                                                                     out entry))
                    {
                        var sectors = this.Set<Sector>().Local.Where(s => s.IdSector == 1);
     
                        var key = contextAdapter.ObjectContext.CreateEntityKey(entry.EntitySet.Name, dbEntityEntry.Entity);
                        bool success = key.EntityKeyValues.Count() > 0;
                        foreach (var item in key.EntityKeyValues)
                        {
     
                            string value = null;
                            if (item.Value != null && !string.IsNullOrWhiteSpace(value = item.Value.ToString()))
                            {
                                Int64 id = 0;
                                if (Int64.TryParse(value, out id) && id <= 0)
                                {
                                    success = false;
                                    break;
                                }
                            }
                            else
                            {
                                success = false;
                                break;
                            }
                        }
     
                        if (success)
                            this.Attach(dbEntityEntry.Entity);
                    }
                }
                return base.SaveChanges();
                
            }
    

       This code solve my problem with entities that have id>0 and isn't attached in current context. Now other problem apear and I'm confusing. Some times, when I call 

    this.Attach(dbEntityEntry.Entity);

    I received an Exception talking about existing key in context, this happend when I try to add an entity with id>0 and I have had use this entity, see this example:

     

       var firstCity = contex.States.FirstOrDefault();
                    
                    City newCity = new City();
                    
                    newCity.Description = "New Jersey";
                    
                    newCity.State = new State() {IdState = 438};
     
                    contex.States.Attach(newCity.State);
    //An object with the same key already exists in the ObjectStateManager.
    The ObjectStateManager cannot track multiple objects with the same key.
                    contex.Cities.Add(newCity);                 contex.SaveChanges();

     

     

     

    I will send for you an example with this scenarios.

     

    Thanks.

     

     


    Michel Magalhães
    Tuesday, September 27, 2011 1:48 AM
  • Thanks for the detailed reply. Sugget you to check this case for more detailed information. http://stackoverflow.com/questions/6033638/an-object-with-the-same-key-already-exists-in-the-objectstatemanager-the-objects

    Thanks,


    Larcolais Gong[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, September 27, 2011 6:54 AM
  • Larcolais,

     

    I know these problems and how can I solve it. I found my problems descriptions on this web site:

    http://agilenet.wordpress.com/2011/07/04/the-pain-and-problems-of-wcf-and-entity-framework-code-first/

    I'm working in a big project and we are changing from Entity 4 to Code First. We use repository pattern,DDD and other patterns and I think that our data access provider have to solve this simple problem, but how I saw, we have to do some workarounds and I'm worried. I don't care if in other service or repository, someone have gotten an entity with the same id.

    What is your opnion about these problems? You really think that I have to worry with attached entities? How can you control this in an big application with some services and repositories?

     

    I'm really interesting to solve this problem, but I have to decide about EF or Nhibernate.

     

    Thank you very much.


    Michel Magalhães
    Tuesday, September 27, 2011 1:10 PM