I am looking to see if there is away to force the AsNoTracking in a static class ? I know there are other ways of doing it but, this is used all over the application. This is just basic example. SearchTest().Search()
private IQueryable<SomeModel> SearchTest()
{
return (from t in _dbContext.test
select new SomeModel()
{
a.test1
}).AsQueryable();
}
public static async Task<SomeModel> Search<T>(this IQueryable<T> query)
{
return new SomeModel(){ Count=await query.CountAsync()};
}
Related
I experienced poor performance when using em.find(entity, primaryKey).
The reason seems to be that em.find() will also load entity collections, that are annotated with FetchType.LAZY.
This small test case illustrates what I mean:
public class OriginEntityTest4 {
[..]
#Test
public void test() throws Exception {
final OriginEntity oe = new OriginEntity("o");
final ReferencePeakEntity rpe = new ReferencePeakEntity();
oe.getReferencePeaks().add(rpe);
DatabaseAccess.onEntityManager(em -> {
em.persist(oe);
em.persist(rpe);
});
System.out.println(rpe.getEntityId());
DatabaseAccess.onEntityManager(em -> {
em.find(OriginEntity.class, oe.getEntityId());
});
}
}
#Access(AccessType.PROPERTY)
#Entity(name = "Origin")
public class OriginEntity extends NamedEntity {
[..]
private final ListProperty<ReferencePeakEntity> referencePeaks =
referencePeaks =
new SimpleListProperty<>(FXCollections.observableArrayList(ReferencePeakEntity.extractor()));
#Override
#OneToMany(mappedBy = "origin", fetch = FetchType.LAZY)
public final List<ReferencePeakEntity> getReferencePeaks() {
return this.referencePeaksProperty().get();
}
public final void setReferencePeaks(final List<ReferencePeakEntity> referencePeaks) {
this.referencePeaksProperty().setAll(referencePeaks);
}
}
I cannot find any documentation on that, my question is basically how can I prevent the EntityManager from loading the lazy collection?
Why I need em.find()?
I use the following method to decide whether I need to persist a new entity or update an existing one.
public static void mergeOrPersistWithinTransaction(final EntityManager em, final XIdentEntity entity) {
final XIdentEntity dbEntity = em.find(XIdentEntity.class, entity.getEntityId());
if (dbEntity == null) {
em.persist(entity);
} else {
em.merge(entity);
}
}
Note that OriginEntity is a JavaFX bean, where getter and setter delegate to a ListProperty.
Because FetchType.LAZY is only a hint. Depending on the implementation and how you configured your entity it will be able to do it or not.
Not an answer to titles question but maybe to your problem.
You can use also em.getReference(entityClass, primaryKey) in this case. It should be more efficient in your case since it just gets a reference to possibly existing entity.
See When to use EntityManager.find() vs EntityManager.getReference()
On the other hand i think your check is perhaps not needed. You could just persist or merge without check?
See JPA EntityManager: Why use persist() over merge()?
I'm trying to make a base class for crud ops but can't quite figure out how to get this part wired up or if it's possible. I'm using an EDMX w/ generated dbcontexts and pocos, so, ideally, I'd like to create a base class from where I can derive all my crud methods.
Interface:
public interface IGenericCrud<T> where T : class
{
void Add(T entity);
}
Implementation:
public abstract class MyImplementation : IGenericCrud<KnownModel>
{
protected myEntities context;
public MyImplementation()
{
context = new myEntities();
}
void Add(KnownModel entity)
{
// This doesn't work, but it's what I'd like to accomplish
// I'd like to know if this possible without using ObjectContexts
context.KnownModel(add entity);
}
}
I believe you should look into the repository pattern. That seems to be what you are looking for.
Here's the thing.
I have an interface, and I would to put the Include extension method, who belongs to EntityFramework library, to my IRepository layer wich dont needs to knows about EntityFramework.
public interface IRepository<TEntity>
{
IQueryable<TEntity> Entities { get; }
TEntity GetById(long id);
TEntity Insert(TEntity entity);
void Update(TEntity entity);
void Delete(TEntity entity);
void Delete(long id);
}
So I have the extension method:
public static class IncludeExtension
{
static IQueryable<TEntity> Include<TEntity>(this IQueryable<TEntity> query,
string path)
{
throw new NotImplementedException();
}
}
But I don't know how to implement it in this layer, and I would to send it to my EntityFramework (or whatever who will implement the IRepository) to deal with.
I need same to a Interface with a extension method.
Any light?
Include is leaky abstraction and it works only with Entity framework. EF 4.1 already contains Include over generic IQueryable but it internally only converts passed generic IQueryable to generic ObjectQuery or DbQuery and calls their Include.
Here is some example how to wrap that include in repository (repository implementation is dependent on EF so it can use Include provided by EF directly).
This question is a bit old, but here are two EF-independent solutions if you or anyone else is still looking:
1. Reflection-based Solution
This solution is what the .NET Framework falls back to if the IQueryable does not cast to a DbQuery or ObjectQuery. Skip these casts (and the efficiency it provides) and you've decoupled the solution from Entity Framework.
public static class IncludeExtension
{
private static T QueryInclude<T>(T query, string path)
{
MethodInfo includeMethod = query.GetType().GetMethod("Include", new Type[] { typeof(string) });
if ((includeMethod != null) && typeof(T).IsAssignableFrom(includeMethod.ReturnType))
{
return (T)includeMethod.Invoke(query, new object[] { path });
}
return query;
}
public static IQueryable<T> Include<T>(this IQueryable<T> query, string path) where T : class
{
return QueryInclude(query, path);
}
// Add other Include overloads.
}
2. Dyanmics-based Solution
Here the QueryInclude<T> method uses the dynamic type to avoid reflection.
public static class IncludeExtension
{
private static T QueryInclude<T>(T query, string path)
{
dynamic querytWithIncludeMethod = query as dynamic;
try
{
return (T)querytWithIncludeMethod.Include(path);
}
catch (RuntimeBinderException)
{
return query;
}
}
public static IQueryable<T> Include<T>(this IQueryable<T> query, string path) where T : class
{
return QueryInclude(query, path);
}
// Add other Include overloads.
}
In Entity Framework 5.0 they now provide an extension method to IQueryable to add the Include functionality. You will just need to add a using "System.Data.Entity" in order to resolve the extension method. For direct documentation go here
I'm using StructureMap to resolve references to my repository class. My repository interface implements IDisposable, e.g.
public interface IMyRepository : IDisposable
{
SomeClass GetById(int id);
}
An implementation of the interface using Entity Framework:
public MyRepository : IMyRepository
{
private MyDbContext _dbContext;
public MyDbContext()
{
_dbContext = new MyDbContext();
}
public SomeClass GetById(int id)
{
var query = from x in _dbContext
where x.Id = id
select x;
return x.FirstOrDefault();
}
public void Dispose()
{
_dbContext.Dispose();
}
}
Anyway as mentioned I'm using StructureMap to resolve IMyRepository. So when, where and how should I call my dispose method?
WARNING: please note that my views have changed, and you should consider the following advise outdated. Please see this answer for an updated view: https://stackoverflow.com/a/30287923/264697
While DI frameworks can manage lifetime of objects for you and some could even dispose objects for you after you're done using with them, it makes object disposal just too implicit. The IDisposable interface is created because there was the need of deterministic clean-up of resources. Therefore, in the context of DI, I personally like to make this clean-up very explicit. When you make it explicit, you've got basically two options: 1. Configure the DI to return transient objects and dispose these objects yourself. 2. Configure a factory and instruct the factory to create new instances.
I favor the second approach over the first, because especially when doing Dependency Injection, your code isn't as clean as it could be. Look for instance at this code:
public sealed class Client : IDisposable
{
private readonly IDependency dependency;
public Client(IDependency dependency)
{
this. dependency = dependency;
}
public void Do()
{
this.dependency.DoSomething();
}
public Dispose()
{
this.dependency.Dispose();
}
}
While this code explicitly disposes the dependency, it could raise some eyebrows to readers, because resources should normally only be disposed by the owner of the resource. Apparently, the Client became the owner of the resource, when it was injected.
Because of this, I favor the use of a factory. Look for instance at this example:
public sealed class Client
{
private readonly IDependencyFactory factory;
public Client(IDependencyFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (var dependency = this.factory.CreateNew())
{
dependency.DoSomething();
}
}
}
This example has the exact same behavior as the previous example, but see how the Client class doesn't have to implement IDisposable anymore, because it creates and disposes the resource within the Do method.
Injecting a factory is the most explicit way (the path of least surprise) to do this. That's why I prefer this style. Downside of this is that you often need to define more classes (for your factories), but I personally don't mind.
RPM1984 asked for a more concrete example.
I would not have the repository implement IDisposable, but have a Unit of Work that implements IDisposable, controls/contains repositories and have a factory that knows how to create new unit of works. With that in mind, the above code would look like this:
public sealed class Client
{
private readonly INorthwindUnitOfWorkFactory factory;
public Client(INorthwindUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (NorthwindUnitOfWork db =
this.factory.CreateNew())
{
// 'Customers' is a repository.
var customer = db.Customers.GetById(1);
customer.Name = ".NET Junkie";
db.SubmitChanges();
}
}
}
In the design I use, and have described here, I use a concrete NorthwindUnitOfWork class that wraps an IDataMapper that is the gateway to the underlying LINQ provider (such as LINQ to SQL or Entity Framework). In sumary, the design is as follows:
An INorthwindUnitOfWorkFactory is injected in a client.
The particular implementation of that factory creates a concrete NorthwindUnitOfWork class and injects a O/RM specific IDataMapper class into it.
The NorthwindUnitOfWork is in fact a type-safe wrapper around the IDataMapper and the NorthwindUnitOfWork requests the IDataMapper for repositories and forwards requests to submit changes and dispose to the mapper.
The IDataMapper returns Repository<T> classes and a repository implements IQueryable<T> to allow the client to use LINQ over the repository.
The specific implementation of the IDataMapper holds a reference to the O/RM specific unit of work (for instance EF's ObjectContext). For that reason the IDataMapper must implement IDisposable.
This results in the following design:
public interface INorthwindUnitOfWorkFactory
{
NorthwindUnitOfWork CreateNew();
}
public interface IDataMapper : IDisposable
{
Repository<T> GetRepository<T>() where T : class;
void Save();
}
public abstract class Repository<T> : IQueryable<T>
where T : class
{
private readonly IQueryable<T> query;
protected Repository(IQueryable<T> query)
{
this.query = query;
}
public abstract void InsertOnSubmit(T entity);
public abstract void DeleteOnSubmit(T entity);
// IQueryable<T> members omitted.
}
The NorthwindUnitOfWork is a concrete class that contains properties to specific repositories, such as Customers, Orders, etc:
public sealed class NorthwindUnitOfWork : IDisposable
{
private readonly IDataMapper mapper;
public NorthwindUnitOfWork(IDataMapper mapper)
{
this.mapper = mapper;
}
// Repository properties here:
public Repository<Customer> Customers
{
get { return this.mapper.GetRepository<Customer>(); }
}
public void Dispose()
{
this.mapper.Dispose();
}
}
What's left is an concrete implementation of the INorthwindUnitOfWorkFactory and a concrete implementation of the IDataMapper. Here's one for Entity Framework:
public class EntityFrameworkNorthwindUnitOfWorkFactory
: INorthwindUnitOfWorkFactory
{
public NorthwindUnitOfWork CreateNew()
{
var db = new ObjectContext("name=NorthwindEntities");
db.DefaultContainerName = "NorthwindEntities";
var mapper = new EntityFrameworkDataMapper(db);
return new NorthwindUnitOfWork(mapper);
}
}
And the EntityFrameworkDataMapper:
public sealed class EntityFrameworkDataMapper : IDataMapper
{
private readonly ObjectContext context;
public EntityFrameworkDataMapper(ObjectContext context)
{
this.context = context;
}
public void Save()
{
this.context.SaveChanges();
}
public void Dispose()
{
this.context.Dispose();
}
public Repository<T> GetRepository<T>() where T : class
{
string setName = this.GetEntitySetName<T>();
var query = this.context.CreateQuery<T>(setName);
return new EntityRepository<T>(query, setName);
}
private string GetEntitySetName<T>()
{
EntityContainer container =
this.context.MetadataWorkspace.GetEntityContainer(
this.context.DefaultContainerName, DataSpace.CSpace);
return (
from item in container.BaseEntitySets
where item.ElementType.Name == typeof(T).Name
select item.Name).First();
}
private sealed class EntityRepository<T>
: Repository<T> where T : class
{
private readonly ObjectQuery<T> query;
private readonly string entitySetName;
public EntityRepository(ObjectQuery<T> query,
string entitySetName) : base(query)
{
this.query = query;
this.entitySetName = entitySetName;
}
public override void InsertOnSubmit(T entity)
{
this.query.Context.AddObject(entitySetName, entity);
}
public override void DeleteOnSubmit(T entity)
{
this.query.Context.DeleteObject(entity);
}
}
}
You can find more information about this model here.
UPDATE December 2012
This an an update written two years after my original answer. The last two years much has changed in the way I try to design the systems I'm working on. Although it has suited me in the past, I don't like to use the factory approach anymore when dealing with the Unit of Work pattern. Instead I simply inject a Unit of Work instance into consumers directly. Whether this design is feasibly for you however, depends a lot on the way your system is designed. If you want to read more about this, please take a look at this newer Stackoverflow answer of mine: One DbContext per web request…why?
If you want to get it right, i'd advise on a couple of changes:
1 - Don't have private instances of the data context in the repository. If your working with multiple repositories then you'll end up with multiple contexts.
2 - To solve the above - wrap the context in a Unit of Work. Pass the unit of work to the Repositories via the ctor: public MyRepository(IUnitOfWork uow)
3 - Make the Unit of Work implement IDisposable. The Unit of Work should be "newed up" when a request begins, and therefore should be disposed when the request finishes. The Repository should not implement IDisposable, as it is not directly working with resources - it is simply mitigating them. The DataContext / Unit of Work should implement IDispoable.
4 - Assuming you are using a web application, you do not need to explicitly call dispose - i repeat, you do not need to explicitly call your dispose method. StructureMap has a method called HttpContextBuildPolicy.DisposeAndClearAll();. What this does is invoke the "Dispose" method on any HTTP-scoped objects that implement IDisposable. Stick this call in Application_EndRequest (Global.asax). Also - i believe there is an updated method, called ReleaseAllHttpScopedObjects or something - can't remember the name.
Instead of adding Dispose to IMyRepository, you could declare IMyRepository like this:
public interface IMyRepository: IDisposable
{
SomeClass GetById(int id);
}
This way, you ensure all repository will call Dispose sometimes, and you can use the C# "using" pattern on a Repository object:
using (IMyRepository rep = GetMyRepository(...))
{
... do some work with rep
}
I am looking into creating an Entity Framework 4 generic repository for a new ASP.NET MVC project i am working on. I have been looking at various tutorials and they all seem to use the Unit of Work pattern ...
From what i have been reading, EF is using this already within the ObjectContext and you are simply extending this to make your own Units of Work.
Source: http://dotnet.dzone.com/news/using-unit-work-pattern-entity?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+zones%2Fdotnet+(.NET+Zone)
Why would one go to the effort of doing this?
Is this the preferred way of working with generic repositories?
Many thanks,
Kohan.
This is not the way I would work with generic repositories. First of all, I would share ObjectContext between ClassARepository, CalssBRepository and other repositories in current request. Using IOC container, using injection and per request behavior is recommended:
This is how my generic repositories look like:
public interface IRepository<T>
{
//Retrieves list of items in table
IQueryable<T> List();
IQueryable<T> List(params string[] includes);
//Creates from detached item
void Create(T item);
void Delete(int id);
T Get(int id);
T Get(int id, params string[] includes);
void SaveChanges();
}
public class Repository<T> : IRepository<T> where T : EntityObject
{
private ObjectContext _ctx;
public Repository(ObjectContext ctx)
{
_ctx = ctx;
}
private static string EntitySetName
{
get
{
return String.Format(#"{0}Set", typeof(T).Name);
}
}
private ObjectQuery<T> ObjectQueryList()
{
var list = _ctx.CreateQuery<T>(EntitySetName);
return list;
}
#region IRepository<T> Members
public IQueryable<T> List()
{
return ObjectQueryList().OrderBy(#"it.ID").AsQueryable();
}
public IQueryable<T> List(params string[] includes)
{
var list = ObjectQueryList();
foreach(string include in includes)
{
list = list.Include(include);
}
return list;
}
public void Create(T item)
{
_ctx.AddObject(EntitySetName, item);
}
public void Delete(int id)
{
var item = Get(id);
_ctx.DeleteObject(item);
}
public T Get(int id)
{
var list = ObjectQueryList();
return list.Where("ID = #0", id).First();
}
public T Get(int id, params string[] includes)
{
var list = List(includes);
return list.Where("ID = #0", id).First();
}
public void SaveChanges()
{
_ctx.SaveChanges();
}
#endregion
}
ObjectContext is injected through constructor. List() methods return IQueryable for further processing in business layer (service) objects. Service layer returns List or IEnumerable, so there is no deferred execution in views.
This code was created using EF1. EF4 version can be a little different and simpler.