开发者

Can I create a new object with the results of a query?

If there's a better way to do this, let me know, but this is kind of how i envisioned it. Can it be done?

Customer is a table in the database/datacontext. What I want is to query that table and build a new object with it.

If i were to insert a record, I would do something like this:

Customer cust = new Customer(){ FirstName = "A", LastName = "B", Age = 31 }
db.Customers.InsertOnSubmit(cust);
db.SubmitChanges();

What I want to do is instantiate that object with a query result. Something like this:

var query =
     from a in db.Customers
     where a.FirstName == "A"
     select a;

Customer cust = new Customer(){ query };

or maybe even

Customer cust = new Customer(){
     fr开发者_开发百科om a in db.Customers
     where a.FistName == "A"
     select a;
}

is there some way to do this?


yes, like this:

var query =  from c in db.Customers
     where c.FirstName == "somecriteria"
     select new Customer()
     {
        FirstName = "somevalue",
     };

you can also make totally anonymous objects as well...

var query =  from c in db.Customers
     where c.FirstName == "somecriteria"
     select new() 
     {
        FirstName = c.SomeProperty,
        AnotherProperty=c.AnotherProperty,
     };


There is no built in way to clone objects in the manner you want

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();

Besides this method you could add a new Customer constructor that took a Customer as a parameter to do this or add a helper for cloning.

Lastly, you can consider using AutoMapper for this.


db.Customers
    .Where(x => x.FirstName == "A")
    .Select(x => new Customer{ FirstName =x.FirstName , LastName = x.LastName, Age = x.Age})
    .FirstOrDefault();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜