Loading object in constructor EF 4.1
Sample object...
public class Ball
{
public int Id { get; set; }
public String Name { get; set; }
public Ball()
{
}
public Ball(int id)
{
using (var ctx = new MyContext())
{
var theBall = (from b in ctx.Balls
where b.Id == id
select b).Singl开发者_StackOverflow中文版eOrDefault();
//How do i now map this to 'this'?
}
}
public static Ball Load(int id)
{
using (var ctx = new MyContext())
{
return (from b in ctx.Balls
where b.Id == id
select b).SingleOrDefault();
}
}
}
public void Main()
{
//Not preferred
Ball firstBall = Ball.Load(1);
//Preferred
Ball secondBall = new Ball(1);
}
If you take a look inside the Public Ball constructor which requires an Id to be passed in, is there any way to map the returned object to this class? Without me doing manual assignment of properties... or do i have to use the Static Load method?
Cheers, D
No you cannot map it to constructed instance (EF must create instance itself so you will always end with two instances) unless you manually assign each value like from returned instance to current instance but anyway that is wrong implementation because constructor should be dumb and it should not perform any heavy operation like database queries.
精彩评论