[C#] Linq doesn't insert associated entity on insert.
- by Tomek
Hello!
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?