简体   繁体   中英

Linq doesn't insert associated entity on insert

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM