我有两个不同的实体(数据库优先),它们具有完全相同的结构但命名约定不同。有没有办法可以简化查询它们看似重复的代码(即在DoWorkWithSimilar
中)?
我尝试过使用泛型,但是遇到了linq查询的麻烦。此外,我尽可能回避泛型,因为我喜欢更明确。尽管如此,两个类中的DoWorkWithSimilar
方法非常相似。我试图想出一种更好的方法来简化这两个类(DoWorkSimilarOne
和DoWorkSimilarTwo
)但是,由于我对底层类的结构的约束......我正在努力。有没有更好的办法?
public class DoWorkSimilarOne : IDoWork
{
public IUnitOfWork unitOfWork;
public DoWorkSimilarOne(IUnitOfWork _unitOfWork)
{
unitOfWork = _unitOfWork;
}
public IEnumerable<int> DoWorkWithSimilar(IEnumerable<int> otherIds)
{
IEnumerable<int> similarOneIds = unitOfWork.OtherSimilarOnes
.Where(x => otherIds.Contains(x.Other.OtherId))
.SelectMany(x => x.SimilarOnes)
.Select(x => x.SimilarOneId).ToList();
return similarOneIds;
}
}
public class DoWorkSimilarTwo : IDoWork
{
public IUnitOfWork unitOfWork;
public DoWorkSimilarTwo(IUnitOfWork _unitOfWork)
{
unitOfWork = _unitOfWork;
}
public IEnumerable<int> DoWorkWithSimilar(IEnumerable<int> otherIds)
{
IEnumerable<int> similarTwoIds = unitOfWork.OtherSimilarTwos
.Where(x => otherIds.Contains(x.Other.OtherId))
.SelectMany(x => x.SimilarTwos)
.Select(x => x.SimilarTwoId).ToList();
return similarTwoIds;
}
}
public class SimilarOne
{
public int SimilarOneId { get; set; }
public OtherSimilarOnes OtherSimilarOne { get; set; }
}
public class SimilarTwo
{
public int SimilarTwoId { get; set; }
public OtherSimilarTwos OtherSimilarTwo { get; set; }
}
public class Other
{
public int OtherId { get; set; }
}
public class OtherSimilarOnes
{
public int Id { get; set; }
public Other Other { get; set; }
public IEnumerable<SimilarOne> SimilarOnes { get; set; }
}
public class OtherSimilarTwos
{
public int Id { get; set; }
public Other Other { get; set; }
public IEnumerable<SimilarTwo> SimilarTwos { get; set; }
}
public interface IDoWork
{
IEnumerable<int> DoWorkWithSimilar(IEnumerable<int> otherIds);
}
答案 0 :(得分:1)
对我来说,你只需要使你的方法通用并添加一些基类,对吗?
public abstract class ObjectWithId
{
public int Id { get; set; }
}
public class ObjectThatRelates<T> : ObjectWithId
where T : ObjectWithId
{
public int OtherId { get; set; }
public IEnumerable<T> Similar { get; set; }
}
public class Object1 : ObjectWithId
{
public ObjectThatRelates<Object1> { get; set; }
}
public class Object2 : ObjectWithId
{
public ObjectThatRelates<Object2> { get; set; }
}
然后你的方法变成:
public IEnumerable<int> DoWorkWithSimilar<T>(IEnumerable<int> otherIds)
{
IEnumerable<int> similarOneIds = unitOfWork.ObjectThatRelates<T>
.Where(x => otherIds.Contains(x.OtherId))
.SelectMany(x => x.Similar)
.Select(x => x.Id).ToList();
return similarOneIds;
}
当然,您对IUnitOfWork
的定义必须进行更改,以便它可以返回ObjectThatRelates<Object1>
或ObjectThatRelates<Object2>
,但这样可以避免重复工作。