简体   繁体   中英

linq-to-sql InsertOnSubmit

I have an object model that's mapped to a database table. The update query looks like this for now:

public MyObjectModel CreateNewRecord(MyObjectModel TheNewObject)
{
  using (MyDataContext TheDC = new MyDataContext())
  {
    TheDC.MyTable.InsertOnSubmit(TheNewObject);
  }

  return TheNewObject;
}

That code is not working for the insert part (it tells me that InsertOnSubmit has some invalid arguments). In addition, I'd like to return the inserted object so that I can get the value of the primary key of the inserted item.

What do I need to change? Thanks for your help.

Make sure that in MyTable.InsertOnSubmit(TheNewObject) the new object is the type MyTable can recieve. Then call SubmitChanges() :

public MyObjectModel CreateNewRecord(MyObjectModel TheNewObject)
{
  using (MyDataContext TheDC = new MyDataContext())
  {
    TheDC.MyTable.InsertOnSubmit(TheNewObject);
    TheDC.SubmitChanges();
  }

  return TheNewObject;
}

If MyTable is of type Table<ObjectModel> , you can only add objects of type ObjectModel . Try to create your MyObjectModel class with all of its properties in the linq2sql designer.

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