首页 > 解决方案 > 如何解决c#中的实体问题?

问题描述

我想从不同数据库中的值中找到常见的值。并包含不同的数据库值插入其他数据库。

var t1 = dbcontext.Entities
                  .Student
                  .Select(c => new { countrycode = c.countrycode, 
                                     branchcode = c.branchcode }); 

// db changes code
var t2 = dbcontext.Entities
                  .Student
                  .Select(c => new { countrycode = c.countrycode,  
                                     branchcode = c.branchcode }); 

var common = t2.Except(t1); 

List<newtable> mn = new List<newtable>();

但不取共性。除了共性值问题如何解决。

标签: c#entity-framework

解决方案


set operation中选择,您想要:

除了

产生两个序列的集合差,一个集合的元素没有出现在第二个集合中。

a.Except(b); // a U b 

在此处输入图像描述

要比较某些自定义字段的对象集,您必须实现IEqualityComparer<T>.

public class Student                  
{ 
    public string Name { get; set; }
    public int CountryCode { get; set; }
    public int BranchCode  { get; set; }
    public int Code { get; set; }
}

public class StudentComparer : IEqualityComparer<Student>
{
    public bool Equals(Student x, Student y)
    { 
        if (Object.ReferenceEquals(x, y)) return true;
        
        return x != null 
                && y != null 
                && x.CountryCode.Equals(y.CountryCode) 
                && x.BranchCode.Equals(y.BranchCode);
    }

    public int GetHashCode(Student obj)
    {
        int hashCountryCode = obj.CountryCode.GetHashCode();
        int hashBranchCode  = obj.BranchCode.GetHashCode();

        return hashCountryCode ^ hashBranchCode;
    }
}

var toInstertInB = a.Except(b, new StudentComparer());

推荐阅读