-1

我正在研究基于 SOA 的项目,我遇到了一种情况,我将整个对象数组发送到服务器,然后我必须查看哪些对象是新的,哪些我必须更新,因此我正在寻找一些通用函数,它可以让我获得更新、删除或插入属性的列表

4

1 回答 1

1

我在发送具有多个子实体的实体时遇到了同样的问题。挑战在于弄清楚哪些子实体已被更新、添加或删除。这就是我所做的。

  1. 用. IObjectWithState_ ChildEntity(灵感来自于一个pluralsight entityframework 视频)
  2. 拉取实体的服务器端版本。
  3. 调用FindDifference以获取客户端和服务器上子实体的差异

 

IList<ClassTicket> clientSideTickets = /// What received from client
IList<ClassTicket> serverSideTickets = /// What received from database


  var diffTickets = FindDifference(clientSideTickets ,serverSideTickets ,
    (ticket1, ticket2) => ticket1.Id == ticket2.Id,(ticket1, ticket2) => ticket1.Name == ticket2.Name && ticket1.NoOfTicketsAvailable == ticket2.NoOfTicketsAvailable && ticket1.Price == ticket2.Price);

public interface IObjectWithState
{
    State State { get; set; }
}


// My Child Entity
public class ClassTicket: IObjectWithState
  {
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public short NoOfTicketsAvailable { get; set; }
    public State State { get; set; }
}


public static IEnumerable<T> FindDifference<T>(IEnumerable<T> clientList, IEnumerable<T> serverList, Func<T, T, bool> identityDetector, Func<T, T, bool> changeDetector) where T : IObjectWithState
{
    var finalList = new List<T>();
    var clientItems = clientList as T[] ?? clientList.ToArray();
    var serverItems = serverList as T[] ?? serverList.ToArray();
    foreach (var clientItem in clientItems)
    {
        bool foundInServerList = false;
        foreach (var serverItem in serverItems)
        {
            if(identityDetector(clientItem, serverItem))
            {
                foundInServerList = true;
                clientItem.State = !changeDetector(clientItem, serverItem) ? State.Modified : State.Unchanged;
                finalList.Add(clientItem);
                break;
            }
        }
            if(!foundInServerList)
            {
                clientItem.State = State.Added;
                finalList.Add(clientItem);
            }
        }


foreach (var serverItem in serverItems)
{
    var foundInClientList = clientItems.Any(clientItem => identityDetector(serverItem, clientItem));
    if (!foundInClientList)
    {
        serverItem.State = State.Deleted;
        finalList.Add(serverItem);
    }
}
    return finalList;
}
于 2013-05-24T09:55:46.907 回答