我对 Entity Framework 相当陌生,并且正在研究将一些遗留数据访问代码转换为使用 EF。我想知道在 EF 中是否可以执行以下操作,如果可以,如何操作。假设我有一个这样的客户表
CustomerId | ProductId | StartDate | EndDate
--------------------------------------------
100 | 999 | 01/01/2012| null
假设我还从其他地方(如 XML 文件)加载产品数据作为产品对象的缓存。
public class Customer
{
public int CustomerId {get;set;}
public int Product {get;set}
public DateTime StartDate {get;set;}
public DateTime? EndDate {get;set;}
}
public class Product
{
public int ProductId {get;set;}
public int Description {get;set}
}
目前在 CustomerDal 类中,该方法使用 StoredProc 来获取这样的 Customer 对象
Customer GetCustomer(int customerId)
{
// setup connection, command, parameters for SP, loop over datareader
Customer customer = new Customer();
customer.CustomerId = rdr.GetInt32(0);
int productId = rdr.GetInt32(1);
// ProductCache is a singleton object that has been initialised before
customer.Product = ProductCache.Instance.GetProduct(productId);
customer.StartDate = rdr.GetDateTime(2);
customer.EndDate = rdr.IsDbNull(3) ? (DateTime?)null : rdr.GetDateTime(3);
return customer;
}
我的问题是,当它实现 Customer 对象时,这可能使用 EF,它设置 Product 属性不是来自数据库,而是通过另一种方法,在这种情况下来自内存缓存。同样,当保存一个新的客户对象时,它只从 Products 属性中获取 ProductId 并将值保存在 DB 中。