简体   繁体   中英

Insert record into the table using Entity Framework

I have a DbContext object which has a table called 'Employees'.

I have an employee object which I want to insert into the Employees tables.

I cannot use the Employees directly from the context. I want to access with the table name: is this possible ?

 MyContext _ctx;
 Type employee = a.GetType("SC.Employee"));
 object employee = Newtonsoft.Json.JsonConvert.DeserializeObject(emp, employee);

 using (_ctx = new MyContext())
 {
     //I am trying to insert the employee object to my entity. But this doesn't work
     //_customCtx["Employees"].add(employee);
 }

If i understand your question, you want to deserialize a Json to an Employee Object first, then save this into your context ?

I recommend you to do some like this

Employee myNewEmployee = JsonConvert.DeserializeObject<Employee>(json_string);

using (var _ctx = new MyContext())
{
   _ctx.Employee.Add(myNewEmployee);
}

Even if, as you said, 'I want to decide the entity on runtime based on the json object I receive' you need the table Employees as an entry point.

So in the context add DbSet<Employee> Employees .

Then if the entity you have to work with is determined dynamically you can use reflection to search for 'Employees' on your MyContext type and then work with the selected entity (maybe with dynamics). But you tipically have a finite sets of Entity to work with so why don't just write ifs to select work with the right entity?

This by the way feels like you are not structuring things the right way at another level or in other places

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