我有一个 DataContext 和一个表,定义如下:
public class MyDataContext : DataContext
{
public Table<MyItem> MyItems;
public MyDataContext(string location) : base(location) { }
}
[Table(Name = "MyItems")]
public class MyItem
{
// ID
private string id;
[Column(Storage = "id", IsPrimaryKey = true, IsDbGenerated = true, DbType = "int NOT NULL IDENTITY")]
public string Id
{
get { return id; }
private set { id = value; }
}
private MyDataContext db;
private MyTransitiveObject obj;
public MyItem() {}
public MyItem(MyDataContext db, MyTransitiveObject obj)
{
this.db = db;
this.obj = obj;
}
}
当我为表创建一个新表时,无论如何我调用构造函数MyItem
都没有问题:MyItem(MyDataContext db, MyTransitiveObject obj)
MyDataContext db = new MyDataContext(someLocation);
MyItem myItem = new MyItem(db, someObj);
db.MyItems.Add(myItem);
db.SubmitChanges();
但是,如果我想从数据库中检索一堆行,传递成员当然不会被设置。不过,在对检索到的对象进行任何工作之前,我需要初始化它们。
我能想到的唯一解决方案是使成员成为全局成员,并在对它们进行任何其他操作之前遍历所有查询的对象并设置它们。但这并不整洁:
var q =
from c in db.Customers
select c;
var list = q.ToList();
foreach (MyItem m in list)
{
q.Db = db;
q.Obj = someObj;
}
/* Do something with list */
有什么想法最好的处理方法是什么?