您的位置:首页 > 数据库

c# 获取更新数据库信息

2014-05-07 10:01 309 查看
通过ObjectHelper类对数据库信息进行拷贝和赋值

//新增

public static int CreateUser(JsonUser user){

using (TeleMedicineEntities context = new TeleMedicineEntities())

{

User u = context.User.Create();

ObjectHelper.CopyToObject<User>(user,ref u);

c= context.User.Add(c);

context.SavaChanges();

return c.Id;

}

}

//查询

public static JsonUser RetrieveUser(string accountName, string password, int role)

{

using (TeleMedicineEntities context = new TeleMedicineEntities())

{

var user = (from u in context.User

where u.EmployeeNo == accountName && u.Role == role

select u).FirstOrDefault();

if (user == null)

return null;

else

{

JsonUser ju = new JsonUser();

ObjectHelper.CopyToObject<JsonUser>(user, ref ju);

return ju;

}

}

}

/// <summary>

/// 修改用户

/// </summary>

/// <returns></returns>

public static bool UpdateUsers(JsonUser user)

{

bool result = false;

using (TeleMedicineEntities context = new TeleMedicineEntities())

{

User c = context.User.Find(user.Id);

if (c != null)

{

ObjectHelper.CopyToObject<User>(user, ref c);

result = (context.SaveChanges() == 1);

}

}

return result;

}

---------------------------------------------------------------------------------------------------------

class ObjectHelper

{

/// <summary>

/// Copy an object to destination object, only matching fields will be copied

/// </summary>

/// <typeparam name="T"></typeparam>

/// <param name="sourceObject">An object with matching fields of the destination object</param>

/// <param name="destObject">Destination object, must already be created</param>

public static void CopyToObject<T>(object sourceObject, ref T destObject)

{

// If either the source, or destination is null, return

if (sourceObject == null || destObject == null)

return;

// Get the type of each object

Type sourceType = sourceObject.GetType();

Type targetType = destObject.GetType();

// Loop through the source properties

foreach (PropertyInfo p in sourceType.GetProperties())

{

// Get the matching property in the destination object

PropertyInfo targetObj = targetType.GetProperty(p.Name);

// If there is none, skip

if (targetObj == null)

continue;

// Set the value in the destination

targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);

}

return;

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: