【问题标题】:C# SQL Data Mapping into Visual StudioC# SQL 数据映射到 Visual Studio
【发布时间】:2015-09-17 20:18:35
【问题描述】:

我在某个表中有大量数据列,现在需要将它们映射到 C# Visual Studio。有没有一种简单的方法可以做到这一点,或者它仍然是一项费力的手动任务。这是我的意思的一个例子:

string query = @"UPDATE Buyer 
                SET DealID = @DealID,Title=@Title,FirstName=@FirstName,LastName=@LastName,
               IDNo=@IDNo,Address=@Address,POAddress=@POAddress,HomeTel=@HomeTel,
               WorkTel=@WorkTel,Cell=@Cell,Fax=@Fax,Email=@Email,
               MarritalStatus=@MarritalStatus,SpouseFirstName=@SpouseFirstName,
               SpouseLastName=@SpouseLastName,SpouseWorkTel=@SpouseWorkTel,
               SpouseCell=@SpouseCell,SpouseFax=@SpouseFax,Notes=@Notes,
               id=@id,DealID=@DealID WHERE IDNo = @IDNo";
SqlCommand cm = new SqlCommand(query, cn);
string id = iDNoTextBox.Text;
cm.Parameters.AddWithValue("@DealID", txtDealNo.Text);
cm.Parameters.AddWithValue("@id", iDNoTextBox.Text);
cm.Parameters.AddWithValue("@Title", titleComboBox.Text);
cm.Parameters.AddWithValue("@FirstName", firstNameTextBox.Text);

【问题讨论】:

标签: c# sql sql-update mapping sql-insert


【解决方案1】:

你有一些选择以简单的方式做到这一点

首先:使用EntityFramework等ORM,例如可以使用dapper-dot-net,示例代码:

var dog= connection.Query("select Age = @Age, Id = @Id", new {Age = (int?)null,Id=guid});

插入示例:

connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)",
    new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } }
  ).IsEqualTo(3); // 3 rows inserted: "1,1", "2,2" and "3,3"

第二种:使用SqlParameter类型的数组并将其插入SqlCommand

SqlCommand Comm = new SqlCommand("Command text", new SqlConnection("Connection String");
SqlParameter[] param = {new SqlParameter("@Name","Value"), 
                        new SqlParameter("@Name","Value"),
                            ........
                            };
Comm.Parameters.AddRange(param);

第三:或者写一个好的Sql Assistant并为object-to-relational做一个通用的映射器,反之亦然。那么您可以在运行时动态生成参数,而无需硬编码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    相关资源
    最近更新 更多