我正在與實體框架拼湊在一起,在那裏我創建了一個包含整個系統使用的Business Objects(即Account)的庫。實體框架 - 查詢適配器
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上運行。 –