话说上周,在弄系统,因为是新电脑,就没有沿用以前的VS2010换了2013使用,然后因为更新了数据库表结构,于是对EF的生成的实体进行更新。然后手贱一点而过,结果发现底层运行不聊了。一看原因:AccessBase<T> where T : EntityObject 。
是什么原因了,刚开始看到还是比较晕,这里没有问题啊,怎么会报错呢。然后查找源码发现,EF5 针对实体生成的是Class而非原来的EntityObject。
public partial class SysOperateLog。 其实不晓得这是一种进步或是一种退步的方式。在Linq里面,微软就是根据class来进行相关的操作的。以前比较喜欢Linq,但是长时间用EF也用习惯了。针对以前的EF4的框架,现更新如下:
public bool Update<T>(T entity, string PrimaryKey, object PrimaryKeyValue) where T : class
{
主要针对底层Update方法,因为以前entity:EntityObject是能通过entity 找到主键的,现在肯定是不行了。
Type type = typeof(T);
string strName = entities.Connection.ConnectionString.Replace("name=", "");
EntityKey key = null;
try
{
key = entities.CreateEntityKey(type.Name, entity);
}
catch (Exception ex)
{
throw new Exception("不能找到主键!");
}
直接通过上面的方法找到主键即可。
所有方法封装:
#region 更新实体
public bool Update<T>(T entity, string PrimaryKey, object PrimaryKeyValue) where T : class
{
Type type = typeof(T);
string strName = entities.Connection.ConnectionString.Replace("name=", "");
EntityKey key = null;
try
{
key = entities.CreateEntityKey(type.Name, entity);
}
catch (Exception ex)
{
throw new Exception("不能找到主键!");
}
object propertyValue = null;
T entityFromDB = (T)entities.GetObjectByKey(key);
if (null == entityFromDB)
return false;
PropertyInfo[] properties1 = entityFromDB.GetType().GetProperties();
foreach (PropertyInfo property in properties1)
{
propertyValue = null;
if (null != property.GetSetMethod())
{
PropertyInfo entityProperty =
entity.GetType().GetProperty(property.Name);
if (entityProperty.PropertyType.BaseType ==
Type.GetType("System.ValueType") ||
entityProperty.PropertyType ==
Type.GetType("System.String"))
propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);
if (propertyValue == null)
{
Thread.Sleep(50);
propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);
}
if (null != propertyValue)
{
try
{
string Name = property.Name;// "Reference";
if (Name.IndexOf("Reference") < 0)
{
property.SetValue(entityFromDB, propertyValue, null);
}
}
catch (Exception ex) { }
}
}
}
entities.SaveChanges();
return true;
}
#endregion

本文详细介绍了EF5框架下更新实体类时遇到的问题及解决方法,特别是针对主键查找的变动。从EF4到EF5的过渡中,实体类的生成方式由EntityObject变为Class,导致在更新实体时需要手动处理主键查找的过程。通过代码示例,阐述了如何在更新实体时获取并更新主键,同时提供了关键方法的封装,确保了操作的简洁性和效率。
3331

被折叠的 条评论
为什么被折叠?



