【问题标题】:ASP.NET MVC using more than 1 DataContext Insert MethodASP.NET MVC 使用超过 1 个 DataContext 插入方法
【发布时间】:2014-10-13 05:12:13
【问题描述】:

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

我的主要问题是第一个和第二个实体的属性不同,例如在第一个实体中 sample_table1 包含:“member_id”和“member_code”,第二个实体 sample_table_2 包含“student_id”和“student_code”,这只是命名,属性的值是一样的,所以member_id = student_id, member_code = student_code

例子:

控制器

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)

}

我无法更改第二个实体名称,因为其他人正在制作第二个实体,我无法编辑数据库结构...

非常感谢...

【问题讨论】:

  • 是连接字符串惹的祸吗?问题是什么?

标签: c# asp.net-mvc entity-framework crud datacontext


【解决方案1】:

您可以使用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();

...

【讨论】:

  • 它是否映射所有结构,因为我不想获取所有属性,基本上只有从第一个实体到第二个实体的一些属性
  • 你可以配置这个。设置中有忽略
猜你喜欢
  • 1970-01-01
  • 2018-08-08
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
相关资源
最近更新 更多