Search code examples
c#databaseentity-frameworksql-server-ce

EDM Associations are not stored


Just playing around with entity framework.

Now I have a simple database, containing to Entities

Person (Id, Name)
Profession (Id, Designation)

which has an association on the Id.

I want to give a person a new profession programatically with this code:

using (PersonDataModelContainer dmc = new PersonDataModelContainer())
{
    var pers = new Person() { Id = PersonId };
    dmc.Person.Attach(pers);
    var prof = new Profession() { Id = ProfessionId };
    dmc.Profession.Attach(prof);
    pers.Professions.Add(req);

    var result = dmc.SaveChanges();

    return (result > 0);
};

I'm quite new to EF, so it is possibly quite simple.

the effect is: nothing happens and I do not see any new Association in the associations table.

How can I add a new association from existing entities?

Is there any good documentation on working with that concept?

-edit- found a copy of the database in the bin\debug folder. It doesn't contain associations either. but there seems to be writes to that file each time I fire the update as in the code above.


Solution

  • I guess you should to use this SQL Compact, Identity Columns and Entity Framework

                using (var con = new PersonDataModelContainer())
                {
                    var pers = new Person() { Id = PersonId };
    
                    int pId = 0;
                    if (pers.PersonId > 0)
                    {
                        pers = con.Persons.FirstOrDefault(c => c.PersonId == pers.PersonId);
                        pId = pers.pId;
                    }
                    else
                        pId = con.Users.NextId(c => c.PersonId) + 1;
    
                    if (pers.UserId == 0)
                        con.Persons.AddObject(pers);
                    con.SaveChanges();
                    pId = Persons.PersonId;
    
    
                    var prof = new Profession() { Id = ProfessionId, PersonId = pId };
    
                    int profId = 0;
                    if (prof.PersonId > 0)
                    {
                        prof = con.Professions.FirstOrDefault(c => c.ProfessionId == prof.ProfessionId);
                        profId = prof.PersonId;
                    }
                    else
                        profId = con.Professions.NextId(c => c.ProfessionId) + 1;
    
                    if (prof.ProfessionId == 0)
                        con.Professions.AddObject(prof);
                    con.SaveChanges();
                    prof.ProfessionId = profId;
                }