Linq no inserta la entidad asociada al insertar

I have simple mapping:

     [Table(Name="Person")]
        public class Person
        {
            private int id;
            private int state_id;

            private EntityRef<PersonState> state = new EntityRef<PersonState>();

            [Column(IsPrimaryKey = true, Storage = "id", Name="id", 
                    IsDbGenerated = true, CanBeNull = false)]
            public int ID
            {
                get {   return id; }
                set {   id = value; }
            }

            [Column(Storage="state_id", Name="state_id")]
            public int StateID
            {
               get{ return state_id;}
               set{ state_id = value;}
            }

            [Association( Storage = "state", ThisKey = "StateID", IsForeignKey=true)]
            public PersonState State 
            {
                get { return state.Entity; }
                set { state.Entity = value; }
            }
        }

    [Table(Name = "PersonState")]
    public class PersonState
    {
        private int id;
        private State state;

        [Column(Name="id", Storage="id", IsDbGenerated=true, IsPrimaryKey=true)]
        public int ID
        {
            get { return id; }
            set { id = value; }
        }

        [Column(Name = "date", Storage = "date")]
        public DateTime Date
        {
            get { return date; }
            set { date = value; }
        }

        [Column(Name = "type", Storage = "state")]
        public State State
        {
            get { return state; }
            set { state = value; }
        }
    }

I use this code to insert new person with default state:

private static Person NewPerson()
{
     Person p = new Person();
     p.State = DefaultState(p);

     return p;
}

private static PersonState DefaultState()
{
  PersonState state = new PersonState();

  state.Date = DateTime.Now;
  state.State = State.NotNotified;
  state.Comment = "Default State!";

  return state;
}

Leater in code:

db.Persons.InsertOnSubmit(NewPerson());
db.SubmitChanges();

In database(sqlite) I have all new persons, but state_id of all persons is set to 0, and PersonState table is empty. Why Linq did not insert any State object to database?

preguntado el 08 de enero de 11 a las 15:01

What kind of LINQ do you mean? LINQ to SQL? LINQ to Entities? -

1 Respuestas

It's because you aren't telling it to insert the changes to the PersonState table. I would think that having your entities linked together would make this happen automatically but you may have to trying something like this:

Person p = NewPerson();
db.Person.InsertOnSubmit(p);
if (p.State != null) 
{
 db.PersonState.InsertOnSubmit(p.State);
}
db.SubmitChanges();

Respondido el 08 de enero de 11 a las 19:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.