Function Return void How to Run with Open RIA Domain Service - entity-framework

I have few Functions & Procedures to Run from Silverlight project. I have mapped data in EF6. Now I want to Run these function Using OpenRIA Service. I tried giving annotation like Query, Update, Insert, Delete. One or other function does some of these operations. Few return nothing & Few return data.
I wrote a method to call 1 Function from RIA Domain Service
public void BuildRoute4Rdinv(decimal? hpmsyear, string errorout)
{
this.ObjectContext.BuildRoute4Rdinv(year, ref errorout);
}
What Annotation I should provide in above case. this function doesnt return anything & Have no complex type associated with. [Query] requires Return IEnumarable so i cant provide that.

I think the one you are after is "[Invoke]"
Annotate your function with [Invoke] then a related method will be generated on your client side.

Related

WCF with IOperationInvoker using Entity and Ninject

I have a WCF Service from which I need to log the calls to its methods. For this, I used this solution to be able to track the calls and call my internal audit service, which uses Entity 5.1 and injects the services/repositories/DbContext using Ninject.
My Invoke method looks like this:
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
var methodParams = (instance).GetType().GetMethod(_operationName).GetParameters();
var parameters = new Dictionary<string, object>();
for (var index = 0; index < inputs.Length; index++)
parameters.Add(methodParams[index].Name, inputs[index]);
_auditService.TrackFilterParametersValues(_operation.Parent.Type.FullName, _operationName, _operation.Action, parameters);
return _baseInvoker.Invoke(instance, inputs, out outputs);
}
In my Ninject module I have the internal stuff registered like this:
Bind<IAuditService>().To<AuditeService>().InRequestScope();
Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
Bind<DbContext>().To<MyEntities>().InRequestScope();
Problem comes up when, inside the Repository, I call the dbContext to add the new Audit object like this:
_dbContext.Set<T>().Add(entity);
It errors out claiming that the DbContext has been disposed.
What would be the correct way of registering the DbContext on a WCF Service so it gets registered for an IOperationInvoker??
I have to mention that I have all this declaration the same for the main site I'm feeding up with this backend in MVC4 and it works perfectly (no WCF there). So I'm pretty sure something is needed to be corrected for the WCF lifetime cycle, but not so sure about what.
I found the reason of why this was behaving so nasty: in the chain formed by the IOperationInvoker, IOperationBehavior and IServiceBehavior, I was injecting the AuditService by the constructor of the first 2 of them, but in the latest (IServiceBehavior), since I was decorating the WCF class with it and couldn't overload the constructor, I was using the DependencyResolver to obtain the AuditService with a property like this:
public IAuditService AuditService
{
get { return DependencyResolver.Current.GetService<IAuditService>();
}
Then, when I started to debug, I noticed that the constructors were called when the WCF Test Client was querying the WCF for the WSDL data, but the Invoke method was never called because no web method was being invoked. So the AuditService instance (and DbContext) was all fine during the calls of the constructors, but by the time of invoking a web method and calling the Invoke method of the IOperationInvoker, the DbContext was already disposed long time ago.
My workaround for this was to delete all the references to the AuditService from all constructors and move the property with the DependencyResolver from the ServiceBehavior to the IOperationInvoker implementation. Once I did this, the AuditService is called right when it's needed, never before, and its DbContext is never disposed.
If MyEntities inherits from DbContext, then this should work:
Bind(typeof(DbContext)).To(typeof(MyEntities)).InRequestScope();

Can I intercept Entity Framework when it loads data from the database?

We have a multi-layered application, where all the repositories are based on a (home-grown) GenericRepository base class (where T is an entity in the model), that exposes methods such as GetContext(), GetObjectSet() and so on. We allow the repositories that inherit from this to access the context, as they need to call Include(), as we are passing the data up through a WCF service, so need to load all related entities eagerly.
All of our entities implement an interface that has an Active bool property, and what we want to do is intercept the execution of a query, and filter on the Active property, so that any query only returns entities where this is set to true.
Can this be done? In Lightswitch, which is built on EF, there is an event you can capture that gets fired right down in the depths of the query execution, and allows you to do this sort of filtering. I can't find anything in EF itself that allows this.
Anyone any ideas? Thanks
In EF 5, Include is an extension method on IQueryable, so you can do this:
var query = dbSet.Where( o => o.IsActive ).Include( ... )
That means, you don't have to return a DbSet<T> from your generic repository - it should be ok to return an IQueryable<T>.
If this meets your requirements, you can add a Where clause to your generic repository method:
partial class GenericRepository<T>
{
public IQueryable<T> Query( bool includeInactive = false )
{
return ctx.Set<T>().Where( o => includeInactive || o.IsActive );
}
}
The best way that I can think of doing that would be to have your repository methods take in an Expression (i.e. Expression<Func<T, bool>> predicate). That way you can do all of your queries in the actual repository itself (and thus not allowing client-side code any way of accessing your data layer logic) to which you can add a Where before you return from the repository method to only grab those that are Active.
An example of this style that I've used is the following:
public IQueryable<T> Grab(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
Where DbSet is the actual table that you're trying to query. That way you can add .Where(x => x.Active) to the end of it, have it not execute against the database yet (thank you, deferred execution!) and yet still get the exact records that you're looking for.

Zend - Design Pattern DataMapper & Table Gateway

This is directly out of the Zend Quick Start guide. My question is: why would you need the setDbTable() method when the getDbTable() method assigns a default Zend_Db_Table object? If you know this mapper uses a particular table, why even offer the possibility of potentially using the "wrong" table via setDbTable()? What flexibility do you gain by being able to set the table if the rest of the code (find(), fetchAll() etc.) is specific to Guestbook?
class Application_Model_GuestbookMapper
{
protected $_dbTable;
public function setDbTable($dbTable)
{
if (is_string($dbTable)) {
$dbTable = new $dbTable();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTable = $dbTable;
return $this;
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Guestbook');
}
return $this->_dbTable;
}
... GUESTBOOK SPECIFIC CODE ...
}
class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract
{
protected $_name = 'guestbook_table';
}
Phil is correct, this is known as lazy-loading design pattern. I just implemented this pattern in a recent project, because of these benefits:
When I call on getMember() method, I will get a return value, regardless if it has been set before or not. This is great for method chaining: $this->getCar()->getTires()->getSize();
This pattern offers flexibility in that outside calling code is still able to set member values: $myClass->setCar(new Car());
-- EDIT --
Use caution when implementing the lazy-loading design pattern. If your objects are not properly hydrated, a query will be issued for every piece of data which is NOT available. The best thing to do is tail your db query log, during the dev phase, to ensure the number and type of queries are what you expect. A project I was working on was issuing over 27 queries for a "detail" page, and I had no idea until I saw the queries.
This method is called lazy-loading. It allows a property to remain null until requested unless it is set earlier.
One use for setDbTable() would be testing. This way you could set a mock DB table or something like that.
One addition: if setDbTable() is solely for lazy-loading, wouldn't it make more sense to make it private? That way it will avoid accidental assignment and to wrong table as originally mentioned by Sam.
Should we be compromising the design for the sake of testability?

Cannot expose service method in ADO.NET data service

I am trying to create a method that can be exposed through an ADO.NET data service. No matter what I do, the client cannot see the method that I am exposing. I am out of ideas. Please help:
[WebGet]
public ObjectResult<Product> GetAllProducts()
{
ProductOrdersEntities entities = new ProductOrdersEntities();
return entities.GetAllProducts();
}
I have also kept access open to the methods:
public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
}
Still, when I create a client proxy, it cannot see the method GetAllProducts().
I was told by a developer in the Astoria team that the current code generation tool does not support generating code for service operations. By that time I had already started using the .Execute method to make an explicit HTTP request to invoke the method, and this strategy works fine; just that it is not elegant or typesafe.

Is there a way to generically return all of the records from a table with the Entity Framework

Basically I'd be looking to implement a method like this.
IQueryAble GetQuery<T>(Entities db) or extension method Entities.GetQuery<T>()
This way you could do things like this
public IQueryable<T> GetAll()
{
return yourEntityClasses.GetQuery<T>();
}
which would return a SELECT * FROM query expression and obviously from there you could make addtional generic methods for sorting, pagination, where expressions, etc on top of this would save you from having to repeat the code for these methods for each table. I know SubSonic3 does a very good job of this, but was trying to duplicate some of the functionality in an EntityFramework project I am working on. Only thing I see in EF is CreateQuery and ObjectQuery but both of those require you to pass a querystring in which would require you to know the table name.
Well it is possible to get the string that you need to put into the CreateQuery method automatically.
Basically it is just string.Format("[{0}]",entitySetName);
How do you get the entity set name, assuming you have don't use something called MEST, most people don't, you can use some a functions I wrote in this Tip to get the EntitySet for T and from that the name.
Once you do that it should be pretty trivial for you to write the Extension Method
i.e.
public static IQueryable<T> GetAll<T>(this ObjectContext context)
{
var wkspace = context.MetadataWorkspace;
EntitySet set = wkspace
.GetEntitySets(wkspace.GetCSpaceEntityType<T>())
.Single();
return context.CreateQuery<T>(string.Format("[{0}]",set.Name);
}
See the above tip for the other functions used.
Hope this helps
Alex