Entity Framework EntityKey / Foreign Key problem

前端 未结 3 1166
借酒劲吻你
借酒劲吻你 2020-12-10 07:23

As the result of a form post, I\'m trying to save a new Brand record. In my view, Gender is a dropdown, returning an Integer, which is populated from ViewData(\"gender\")

3条回答
  •  粉色の甜心
    2020-12-10 07:38

    Rather than creating an EntityKey create a stub Gender object (sorry I'm not a VB guy so in C#):

    Gender g = new Gender{ID = Int32.Parse(Request.Form("Gender"))};
    

    Then you attach the Gender to the appropriate EntitySet (the name of property on DB that you get Gender entities from is the string below):

    DB.AttachTo("Genders",g);
    

    This puts the database in the state where the Gender is in the ObjectContext in the unchanged state without a database query. Now you can build a relationship as per normal

    brand.Gender = g;
    DB.AddToBrand(brand);
    DB.SaveChanges();
    

    That is all there is to it. No need to muck around with EntityKeys

    Hope this helps

    Alex

提交回复
热议问题