GetType Equal的方法为两个相同的类返回false - c#

Uth*_*imi 0 c# reflection

我有一个类像: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;

Car*_*Dev 5

通常,EntityFramework会创建所谓的代理类.因此,从DB加载的实体将具有类似的类型System.Data.Entity.DynamicProxy.StoreEntity.StoreDetail_SomeNumbersHere.然而,代理将从您的基类派生,所以您可以

  • 检查数据库中的实体是否可分配给您的班级
  • 关闭代理生成,如果不使用延迟加载(请参阅使用代理)
  • 使用预先构建的工具进行复制(例如AutoMapper)
  • 关闭更改跟踪,如果您只是因为不希望更改最终持久化而复制(通常模型和DTO类不相同)
  • 使用更简单的ORM(例如Dapper)