我有2个具有相同列名的表,例如,表A和表B都有列名“Test”。我想从表A和B中选择列Test到实体类。我怎么能这样做?
答案 0 :(得分:1)
听起来您希望TableA和TableB的两个实体合并为一个新对象。您可以使用.Select()
扩展方法创建新的匿名类型,或者使用已定义的类。
这里的要求是你必须在TableA和TableB之间找到一个共同的属性。在这里,我假设你有类似ID
的东西来匹配它们。
匿名类型
var mergedTests = from a in db.TableA
join b in db.TableB on a.CommonID equals b.CommonID
select new
{ TestFromA = a.Test, TestFromB = b.Test }
.ToList();
现有班级
List<MyCustomTests> mergedTests = from a in db.TableA
join b in db.TableB on a.CommonID equals b.CommonID
select new MyCustomTests
{ TestName= a.Test, ShortName= b.Test }
.ToList();
答案 1 :(得分:0)
class Program
{
static void Main(string[] args)
{
var A = new Data[] {
new Data { Test = 1, Relation = 1 },
new Data { Test = 2, Relation = 2 },
new Data { Test = 3, Relation = 3 },
new Data { Test = 4, Relation = 4 },
new Data { Test = 5, Relation = 5 },
};
var B = new Data[] {
new Data { Test = 2, Relation = 2 },
new Data { Test = 3, Relation = 3 },
new Data { Test = 5, Relation = 5 },
};
var res = from a in A
join b in B on a.Relation equals b.Relation
select new { TestA = a.Test, TestB = b.Test };
}
}
class Data
{
public int Test;
public int Relation;
}