C#SQL数据映射到Visual Studio
我在某个表中有大量的数据列,现在需要将它们映射到C#Visual Studio中。有没有一种简单的方法可以做到这一点,或者这仍然是一项费力的手工任务。以下是我的意思的一个例子:C#SQL数据映射到Visual Studio,c#,sql,sql-update,mapping,sql-insert,C#,Sql,Sql Update,Mapping,Sql Insert,我在某个表中有大量的数据列,现在需要将它们映射到C#Visual Studio中。有没有一种简单的方法可以做到这一点,或者这仍然是一项费力的手工任务。以下是我的意思的一个例子: string query = @"UPDATE Buyer SET DealID = @DealID,Title=@Title,FirstName=@FirstName,LastName=@LastName, IDNo=@IDNo,Address=@Addr
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);
你可以选择用简单的方式来做 首先:使用ORMs,例如
EntityFramework
,例如,您可以使用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助手
,并为对象制作一个通用映射器,将其映射到关系
,反之亦然。然后,您可以在运行时动态生成参数,而无需硬编码。有很多方法可以解决此问题。当然,你需要花一点时间来学习什么是对你最好的。