使用多个DataContext Insert方法的ASP.NET MVC

本文关键字:ASP NET MVC 方法 Insert DataContext | 更新日期: 2023-09-27 18:26:21

所以我最近想尝试使用多个数据库

我的主要问题是第一个和第二个实体的属性不同,所以例如,在第一个实体sample_table1中包含:"member_id"answers"member_code",而第二个主体sample_table2包含"student_id"或"student_code"这只是命名,属性的值是相同的,所以member_id=student_id,member_code=student_coode

示例:

控制器

private MyEntities db = new MyEntities ();
//not sure know by add this one, my controller can connect 2 database, but the intellisense is working when i'm using db2 class
private MyEntities2 db2 = new MyEntities2 ();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateSomething(sample_table1 sample_table1, sample_table2 sample_table2)
{
   if (ModelState.IsValid)
   {
       //insert data to 1st Entities
       db.sample_table1.Add(sample_table1);
       db.SaveChanges();
       //insert data to 2nd Entities
       "???" // because the attribute name on 2nd entities is not the same as the 1st entities, i cannot using either sample_table1 & sample_table2
       db2.SaveChanges();
   }
}

视图

@model 1st_entites_data_model.Models.sample_table1
// i don't know for sure but the 2nd entities data model won't appear when i add view    
@{
    ViewBag.Title = "Create Something";
}
@using (Html.BeginForm("CreateSomething", "test", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    //i'm using only the 1st entities, because there is no need for user input the same data value twice
    @Html.TextBoxFor(model => model.sample_table1.member_id)
    @Html.ValidationMessageFor(model => model.sample_table1.member_id)
    @Html.TextBoxFor(model => model.sample_table1.member_code)
    @Html.ValidationMessageFor(model => model.sample_table1.member_code)
}

我不能更改第二个实体的名称,因为其他人正在制作第二个主体,我不能编辑数据库结构。。。

非常感谢。。。

使用多个DataContext Insert方法的ASP.NET MVC

您可以使用automapper将数据从第一个实体传输到第二个实体。之后,您的代码将是:

   db.sample_table1.Add(sample_table1);
   db.SaveChanges();
   //insert data to 2nd Entities
   var sample_table2 = Mapper.Map<sample_table2>(sample_table1);
   db2.sample_table_2.Add(sample_table2);
   db2.SaveChanges();