替代往返序列化-反序列化

本文关键字:反序列化 序列化 | 更新日期: 2023-09-27 18:11:40

我有一个超过100列(包括blobs)的表,我想只复制几个填充列的对象。现在我通过选择需要的列,并使用Json进行往返序列化和反序列化来实现它。NET,效率不高。处理这种情况的最佳方法是什么?

BL.Case mCase;
BL.Case temp = db.Cases.Select(
               xx => new
               {
                   CaseID = xx.CaseID,
                   FirstName = xx.FirstName,
                   LastName = xx.LastName
              }).FirstOrDefault(u => u.CaseID == CaseID);
mCase = Newtonsoft.Json.JsonConvert.DeserializeObject<BL.Case>(Newtonsoft.Json.JsonConvert.SerializeObject(temp));

替代往返序列化-反序列化

使用AutoMapper

像这样做:

BL.Case mCase = null;
var temp = db.Cases.Select(
                xx => new
                {
                    CaseID = xx.CaseID,
                    FirstName = xx.FirstName,
                    LastName = xx.LastName
                }).FirstOrDefault(u => u.CaseID == CaseID);

if (temp != null)
{
    mCase = Mapper.DynamicMap<BL.Case>(temp);
}

另一个需要更多代码(但可能性能更好)的解决方案是:

如果你只需要一件物品:

BL.Case mCase = null;
var temp = db.Cases.Select(
            xx => new
            {
                CaseID = xx.CaseID,
                FirstName = xx.FirstName,
                LastName = xx.LastName
            }).FirstOrDefault(u => u.CaseID == CaseID);

if (temp != null)
{
    mCase = new Case()
    {
        CaseID = temp.CaseID,
        FirstName = temp.FirstName,
        LastName = temp.LastName,
    };
}

如果您需要多个项目:

var temp = db.Cases.Select(
            xx => new
            {
                CaseID = xx.CaseID,
                FirstName = xx.FirstName,
                LastName = xx.LastName
            }); //Here you can filter your query if you want using Where
var result = temp
.ToList() //This will actually execute the query on the database
.Select(x => new Case() //Now you can do this since now we are working on in-memory data
{
    CaseID = x.CaseID,
    FirstName = x.FirstName,
    LastName = x.LastName
});