我需要使用现有数据库来开发我的.NET应用程序。 dB中的表格使用字符串类型主键。有没有办法用Entity框架实现这个?如果没有,可以用什么替代方法来达到目的?
我的.net框架是4.0,使用实体框架6.0。
答案 0 :(得分:0)
基于带有.NET的SQlServer的示例(使用GUID类型主键)
插入数据:
public int GetData(string username, string projectname, int queryDays)
{
queryDays--;
//连接本地数据库
SqlConnection conn = connectLocaldb.ConnectDataBase();
//打开数据库
conn.Open();
//创建查询语句
SqlCommand querySingleInfo = conn.CreateCommand();
querySingleInfo.CommandText = "SELECT count(commitid) as times FROM MemberCommitBeforeCompiling,member where MemberCommitBeforeCompiling.UserName=" + "'" + username + "' and MemberCommitBeforeCompiling.ProjectName=" + "'" + projectname + "' and MemberCommitBeforeCompiling.username=Member.Username AND DATEADD(d,-" + queryDays + ", CONVERT(varchar(12), getdate(), 111)) <=CONVERT(varchar(12), CommitTime, 111)";
SqlDataReader singleInfoReader = querySingleInfo.ExecuteReader();
//有多行数据,用while循环
while (singleInfoReader.Read())
{
pushTotalOfProject = int.Parse(singleInfoReader["times"].ToString().Trim());
}
//关闭查询
singleInfoReader.Close();
//关闭数据库连接
conn.Close();
return pushTotalOfProject;
}
获取数据的方法:
public bool GetUpdateUserRank(string username, int rank)
{
bool flag = false;
try
{
//连接本地数据库
SqlConnection conn = connectLocaldb.ConnectDataBase();
//打开数据库
conn.Open();
//创建查询语句
SqlCommand querySingleInfo = conn.CreateCommand();
querySingleInfo.CommandText = "Update Member set Rank=" + "'" + rank + "'where username=" + "'" + username + "' ";
SqlDataReader userRankInfo = querySingleInfo.ExecuteReader();
//关闭查询
userRankInfo.Close();
//关闭数据库连接
conn.Close();
flag = true;
}
catch (SqlException e)
{
flag = false;
}
return flag;
}
更新数据的方法:
public bool GetDeleteGroup(string groupName)
{
bool flag = false;
try
{
SqlConnection conn = connectLocaldb.ConnectDataBase();
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "delete MemberGroup where GroupName=" + "'" + groupName + "";
int result = cmd.ExecuteNonQuery();
flag = true;
conn.Close();
}
catch (Exception e)
{
flag = false;
}
return flag;
}
删除数据的方法:
Parameters()
这些是我的演示程序。使用my-project.zip
|
+- my-project
|
+- bin (containing start scripts)
+- lib
+- xyz (folders from src/dist)
方法来阻止SQL注入