i have two simple models that have one-many relation
public class X{
public int id {get;set;}
public virtual Y y{ get; set; }
public string description{get;set;}
}
public class Y{
public int id{get;set;}
public string name{get;set;}
}
and from the entity framework i set the relation
I’m trying to submit a form that creates a new X record with existing Y value
the returned data from the form to the action is the string description and y_id.
on the action when i try to specify the object from the parameters
public ActionResult sth(X x){}
the x.y is set to null (which is expected…) while when i tried the following …
x.y = (from i in Y where i.id == that_id select i).first();
...
db.saveChanges();
the entity framework inserted a new Y record to the database …
i know that i’m doing something wrong … your help will be very appreciated !
It seems an issue with tracking Y objects in the dbContext. how are you generating the collection Y you querying with linq? do you fetch it from the database using a dbContext? or from some other source?
if not, you need to be fetching it using a context or using the Attach() function so it could be properly tracked.
Another question pops up. how come a new Y is inserted? Don’t you have a primary key defined in the database? or is it try to insert then an exception is thrown?
These are my thoughts on the matter.