我有一个类像:StoreDetail它继承自BaseEntity,我添加一个方法BaseEntity将类复制到另一个类,如下:
public abstract class BaseEntity
{
public void Copy(BaseEntity source, BaseEntity destination)
{
var destinationId = destination.Id;
var sourceType = source.GetType();
var destinationType = destination.GetType();
if (sourceType.Equals(destinationType))
{
foreach (var field in sourceType.GetFields())
{
var dstinationField = destinationType.GetField(field.Name);
if (dstinationField == null)
continue;
dstinationField.SetValue(destination, field.GetValue(source));
}
foreach (var field in sourceType.GetProperties())
{
var dstinationField = destinationType.GetProperty(field.Name);
if (dstinationField == null)
continue;
dstinationField.SetValue(destination, field.GetValue(source, null), null);
}
}
destination.Id = destinationId;
}
}
Run Code Online (Sandbox Code Playgroud)
首先,我用这一行检查两个对象的类型:
var sourceType = source.GetType();
var destinationType = destination.GetType();
if (sourceType.Equals(destinationType)){}
Run Code Online (Sandbox Code Playgroud)
但它返回False.我用这样的:
StoreEntity.StoreDetail storeDetailModel = new StoreEntity.StoreDetail();
storeDetail.Copy(storeDetail, storeDetailModel); //storeDetailselect from db
Run Code Online (Sandbox Code Playgroud)
storeDetail 是:
var storeDetail = _storeDetails.Where(row => row.StoreId == transferViewModel.SourceStoreId).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
private IDbSet<StoreEntity.StoreDetail> _storeDetails;
通常,EntityFramework会创建所谓的代理类.因此,从DB加载的实体将具有类似的类型System.Data.Entity.DynamicProxy.StoreEntity.StoreDetail_SomeNumbersHere.然而,代理将从您的基类派生,所以您可以
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |