Я начал использовать Linq to SQL в системе (немного похожей на DDD), которая выглядит (слишком упрощенно) следующим образом:
public class SomeEntity // Imagine this is a fully mapped linq2sql class.
{
public Guid SomeEntityId { get; set; }
public AnotherEntity Relation { get; set; }
}
public class AnotherEntity // Imagine this is a fully mapped linq2sql class.
{
public Guid AnotherEntityId { get; set; }
}
public interface IRepository<TId, TEntity>
{
Entity Get(TId id);
}
public class SomeEntityRepository : IRepository<Guid, SomeEntity>
{
public SomeEntity Get(Guid id)
{
SomeEntity someEntity = null;
using (DataContext context = new DataContext())
{
someEntity = (
from e in context.SomeEntity
where e.SomeEntityId == id
select e).SingleOrDefault<SomeEntity>();
}
return someEntity;
}
}
Теперь у меня проблема. Когда я пытаюсь использовать SomeEntityRepository вот так
public static class Program
{
public static void Main(string[] args)
{
IRepository<Guid, SomeEntity> someEntityRepository = new SomeEntityRepository();
SomeEntity someEntity = someEntityRepository.Get(new Guid("98011F24-6A3D-4f42-8567-4BEF07117F59"));
Console.WriteLine(someEntity.SomeEntityId);
Console.WriteLine(someEntity.Relation.AnotherEntityId);
}
}
все работает нормально, пока программа не дойдет до последней WriteLine, потому что она выдает ObjectDisposedException, потому что DataContext больше не существует.
Я вижу настоящую проблему, но как мне ее решить? Думаю, есть несколько решений, но ни одно из тех, о которых я думал до сих пор, не подошло бы в моей ситуации.
- Get away from the repository pattern and using a new DataContext for each atomic part of work.
- I really would not want to do this. A reason is that I do not want to be the applications to be aware of the repository. Another one is that I do not think making linq2sql stuff COM visible would be good.
- Кроме того, я думаю, что выполнение
context.SubmitChanges(), вероятно, потребует гораздо больше, чем я планировал.
- Specifying DataLoadOptions to fetch related elements.
- As I want my Business Logic Layer to just reply with some entities in some cases, I do not know which sub-properties they need to use.
- Disabling lazy loading/delayed loading for all properties.
- Not an option, because there are quite a few tables and they are heavily linked. This could cause a lot of unnecessary traffic and database load.
- Some post on the internet said that using .Single() should help.
- Apparently it does not ...
Есть ли способ решить эту проблему?
Кстати: мы решили использовать Linq t0 SQL, потому что это относительно легкое ORM-решение, включенное в .NET framework и Visual Studio. Если .NET Entity Framework больше подходит для этого шаблона, возможно, стоит переключиться на него. (Мы еще не так далеки от реализации.)