如果有更好的方法可以做到这一点,请告诉我,但这就是我设想的方式。可以吗?
Customer是数据库/ datacontext中的表。我想要的是查询该表并使用它构建一个新对象。
如果我要插入记录,我会做这样的事情:
Customer cust = new Customer(){ FirstName = "A", LastName = "B", Age = 31 }
db.Customers.InsertOnSubmit(cust);
db.SubmitChanges();
我想要做的是用查询结果实例化该对象。像这样:
var query =
from a in db.Customers
where a.FirstName == "A"
select a;
Customer cust = new Customer(){ query };
或者甚至
Customer cust = new Customer(){
from a in db.Customers
where a.FistName == "A"
select a;
}
有没有办法做到这一点?
答案 0 :(得分:6)
var query = from c in db.Customers
where c.FirstName == "somecriteria"
select new Customer()
{
FirstName = "somevalue",
};
你也可以制作完全匿名的对象......
var query = from c in db.Customers
where c.FirstName == "somecriteria"
select new()
{
FirstName = c.SomeProperty,
AnotherProperty=c.AnotherProperty,
};
答案 1 :(得分:0)
db.Customers
.Where(x => x.FirstName == "A")
.Select(x => new Customer{ FirstName =x.FirstName , LastName = x.LastName, Age = x.Age})
.FirstOrDefault();
答案 2 :(得分:0)
没有内置方法可以按照您想要的方式克隆对象
db.Customers
.Where(x => x.FirstName ="A")
.Select(x => new Customer
{
FirstName = x.FirstName,
LastName = x.LastName,
...
Id = default(x.Id.GetType()) // or copy the Id if you want it
})
.First();
除了这种方法,您还可以添加一个新的Customer构造函数,该构造函数将Customer作为参数来执行此操作或添加帮助程序以进行克隆。
最后,您可以考虑使用AutoMapper。