【发布时间】:2011-10-14 07:24:45
【问题描述】:
我正在为实体框架而苦苦挣扎,我在其中创建了一个包含在整个系统中使用的业务对象(即帐户)的库。
public class Account
{
public long AccountId { get; set; }
public string AccountText { get; set; }
}
实体框架会在请求或需要保存时来回转换它们
public interface EntityAdapter<T> {
T Materialize(long id);
long Dematerialize(T business);
void Dispose(T business);
}
public abstract class EFEntityAdapter<T> : EntityAdapter<T> {
private static MyModel.MyEntities __ctx = null;
protected MyModel.MyEntities _context
{
get
{
if (__ctx == null)
{
__ctx = new MyModel.MyEntities ();
}
return __ctx;
}
}
public abstract T Materialize(long id);
public abstract long Dematerialize(T business);
public abstract void Dispose(T business);
}
public class AccountEntityAdapter : EFEntityAdapter<CommonLib.BusinessModels.Account>
{
public override CommonLib.BusinessModels.Account Materialize(long id)
{
Account entity = (from account in _context.Accounts
where account.AccountId == id
select account).FirstOrDefault();
if (entity == null)
return null;
CommonLib.BusinessModels.Account business = new CommonLib.BusinessModels.Account();
business.AccountId = entity.AccountId;
business.AccountText = entity.AccountText;
return business;
}
public override long Dematerialize(CommonLib.BusinessModels.Account business)
{
long id = business.AccountId;
Account entity = (from account in _context.Accounts
where account.AccountId == id
select account).FirstOrDefault();
if (entity == null)
{
if (id > 0)
{
throw new Exception("Account with id: " + id + " does not exists");
}
else
{
entity = new Account();
_context.Accounts.AddObject(entity);
}
}
entity.AccountId = business.AccountId;
entity.AccountText = business.AccountText;
_context.SaveChanges();
business.AccountId = entity.AccountId;
return entity.AccountId;
}
public override void Dispose(CommonLib.BusinessModels.Account business)
{
long id = business.AccountId;
Account entity = (from account in _context.Accounts
where account.AccountId == id
select account).FirstOrDefault();
if (entity == null)
{
throw new Exception("Account with id: " + id + " was not found, but an attempt to delete it was done");
}
_context.DeleteObject(entity);
_context.SaveChanges();
}
}
但现在我想将适配器与 linq 一起使用,这样我就可以做类似的事情
AccountEntityAdapter a = new AccountEntityAdapter();
List<Commonlib.BusinessModels.Account> list = (from account in a
where account.AccountId > 6
select account).ToList();
这样我就摆脱了实体上下文...
我怎样才能做到这一点?
【问题讨论】:
-
你在重新发明一个轮子。放弃并使用您的实体作为业务对象。如此广泛的复杂性有什么意义?
-
据我所知,实体对象无法从应用程序域中删除,如果我想将信息转移到另一个地方然后返回它并进行一些更改,我必须使用其他对象?
-
确实如此,但查询必须在原始对象上运行,而不是 DTO。
-
没错,但我希望查询返回我的对象而不是实体对象
-
在这种情况下,您必须直接在查询中进行投影,而不是使用映射器,否则您必须使用实体运行查询,然后对调用映射器的结果运行 linq-to-object 查询以转换结果.
标签: c# entity-framework business-objects