I receive the following error when trying to run the new project per the instruction in the Readme file.
1: querying Todos
2: Query failed: The action 'Todos' on controller 'BreezeSample' with return type 'System.Collections.Generic.List`1[[MyTasks.Api.Models.BreezeSampleTodoItem, MyTasks.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' cannot support querying. Ensure the type of the returned content is IEnumerable, IQueryable, or a generic form of either interface.
UPDATE:
I checked my event viewer, and see a SQL error that I've never seen before when trying to debug on my machine -
Login failed for user 'my-machine\user-name'. Reason: Failed to open the explicitly specified database. [CLIENT: ]
It seems that the database being generated by BreezeSamplesContext is inaccessible for some reason? It has been generated by code-first, but I can't query it (apparently).
UPDATE 2:
I've changed the default method to -
[HttpGet]
public IQueryable<BreezeSampleTodoItem> Todos()
{
System.Data.Entity.DbSet<BreezeSampleTodoItem> result = null;
try
{
result = _contextProvider.Context.Todos;
}
catch (Exception exc)
{
throw new Exception(exc.Message);
}
return result;
}
Although the Seed method works, and the database is dropped and repopulated with seed values, I get a response of 0 items in the 'result' above.
UPDATE: December 15
The critical piece of information ... the reason for the problem ... is the use of the pre-release SPA template.
That template is not the same as the MVC 4 Web API or Empty templates that are described in the Breeze documentation
The SPA Template and the MVC update include the beginnings of ASP.NET Web API support for OData queries. Their stab at OData conflicts with Breeze; the two forces are wrestling for ownership of the OData query. Wish we could use theirs but it is missing essential features such as support for $select and $expand.
Fortunately, it is easy to disable the MS version so that Breeze prevails. Open App_Start/WebApiConfig.cs file and delete or comment out the following:
config.EnableQuerySupport(); // conflicts with Breeze's ODataActionFilter
The misleading error about "return type" should disappear and you should be back in business.
Note that taking this step turns off the MS Web API OData filter for the entire site. We have it on our backlog to update the Breeze ODataActionFilterAttribute so that it disables the MS Web API OData handling for the Breeze controller only. We hadn't bothered yet because the SPA template remains unofficial at this time. For the nonce ... you can't mix Breeze and Web API OData queries in the same site ... unless you're prepared to do the per-controller filter cleanup yourself.
We have a Breeze version of the new SPA Template working and almost ready to release. I'll be writing about it shortly and will update this answer with a link.
Below is my previous answer which I preserve mostly because (a) it describes how to diagnose a problem and (b) is the context for the comment chain.
Let's start over and see if we can diagnose. Close all Visual Studio sessions (that should stop IIS Express). Launch a fresh VS session. Create an MVC4 Web Api application in VS 2012. Add the Breeze.MVC4WebApiClientSample NuGet package. Run it (F5). Still having trouble?
If so, let's update the controller method with a new line like this:
[HttpGet]
public IQueryable Todos() {
var items = _contextProvider.Context.Todos.ToList(); // test the query
return _contextProvider.Context.Todos;
}
Put a breakpoint on the var items ... line and re-run with the debugger (F5). Step into that line. Did it throw (not good but interesting)? If not, how many items did you get? Zero? You should have 6.
If you can't get past this point, I don't think this is a Breeze problem. Breeze hasn't done anything yet. I'd be looking for something unexpected in your environment.
Let us know how it stands when you get to this point; if still stuck we'll be ready for next steps.
The sample from NuGet is set up to drop and re-create the database every time you run the code. Do you happen to have the database open in a SQL Management Studio? I ran into this as well.
Take a look at the BreezeSampleDatabaseInitializer class. Check out the comment that talks about preserving the changes between server sessions. If you change the class to implement the DropCreateDatabaseIfModelChanges interface it will only try to drop the database when you change the model.
Related
In the comment of this post (Problem with WCF Data Service (OData), SetEntitySetPageSize and custom operations), it mentioned “OData stable paging”.
I am quite new to OData, and trying to get stable paging in OData query.
By "stable paging", I mean there is an OData database in which new entries are constantly being created, I wanted the paging are not interrupted by the new data creation in the database.
For example, if I get the first page by $top=100, then get second page by $top=100&$skip=100, then the third page by $top=100&$skip=200, in which page size is 100. However, because the database is changing, the data I have skipped may not necessarily be the same data I retrieved from previous requests.
Just like the graph example shows data sorting by entry creation time, the first request and the second request:
I wonder what's the best way to do "Stable Paging"?
Thanks!
My current solution follows this post's recommendation - "Paging Through Results" by Markus Winand:
http://use-the-index-luke.com/sql/partial-results/fetch-next-page
It discussed general solutions to stable paging, although it's not OData specific, it works for my scenario.
I've seen other questions regarding using straight SQL for MVC data access, for example here. Most responses don't answer the question but ask
"Why would you not want to use ORM, EF, Linq, etc?"
My group does custom reporting out of a data warehouse that requires a lot of complex, highly tuned Oracle queries that are manipulated based on user GUI parameter selections.
My newest project is to develop a SQL plugin reporting tool for SQL report developers. They would create a pre-tuned SQL for the report with pseudo parameters and enter (and store) via the GUI. Then the GUI would prompt them for the parameter definitions (name and type) that need to be displayed/requested at run time to ultimately replace the pseudo variables.
So a SQL statement may look like:
SELECT * FROM orders WHERE order date BETWEEN '<Date1>' AND '<Date2>'
And the report developer would then, via the GUI, add two parameters named Date1 and Date2, and flag them as date fields.
End users would then select the report, get prompted for Date1 and Date2, and the GUI would do the substitution and run the SQL.
As you can see, I have no choice but to use straight SQL (especially in the 2nd example and understand I would have to forgo strongly typed in the 2nd also).
So my questions are:
When is it necessary to bypass EF/Linq (and there are definitely reasons to), what is best practice in MVC 4?
And how best to strongly type when I do know the output columns ahead of time?
And CRUD processing?
Can anyone point me to any examples of non-EF/Linq based coding in this regard?
I think this is a bit open ended question, so here's my 2c. (If tl dr, go to last section)
To me, it's not so much "by passing EF/Linq", but rather, the need to choose the appropriate data persistence library. I have used PetaPoco, Ado.Net, NHibernate/ActiveRecord, Linq2Sql, EF (My main choice) with MVC.
Best practice actually comes from realising that Controllers are STILL a part of presentation layer, and that it should not deal with anything other than HttpContext related operations + calling business logic service classes.
I arrange my classes as:
Presentation (MVC) -> Logic Services (Simple classes) -> Data Access (Context wrapped in "repositories").
So I can't quite imagine whether to use EF or not would have any implication on asp.net MVC.
For me, Data Access returns data in DTO, e.g.
public List GetAllFoos()
Whether that method string concatenate from a xml, etc or do a simple Context.Foos.ToList() is irrelevant to the rest of the application. All I care is Data Access do NOT return me a DataSet with string matching for columns. Those stay in DAL.
See point 1 and 2. My repositories have CRUD methods on it. How it's done is irrelevant to the rest of application. Take one of the most basic interface to my repositories classes:
public interface IFooRepository
{
void Save(Foo foo)
Foo Get(int id)
void Create(Foo foo)
void Delete(int id)
}
One point not mentioned yet, DI is also crucial. The concrete implimentation "FooRepository" may choose to request dependencies such as Web services, context classes, etc. Those are, however, again, completely irrelevant to the caller who depends on the interface.
If you still require an example after the 3 points above, drop a comment and I'll whip up something extremely simple using Ado.net.
===========================================================================
To EF or not to EF.
For me, if starting a new project with new schema, I use EF code first.
Fitting new code to old database + old project has no ORM mapping I can reuse = PetaPoco.
===========================================================================
In the context of your project:
The "SQL plugin reporting tool for SQL report developers". "The" sql reporting service? I'm not sure why you need to do anything? Doesn't SSRS already do that? (Enter sql statement/data source, generate form for parameter, etc).
If not I'd question the design decision. IMVHO, the need for users of an application (I don't care if it's "report developer" or w/e) to enter SQL statements is usually stemmed from "architectural astronauts". How do you debug the SQL statement when you enter via GUI as a string? How do you know the tables and the relationships? You either dig into SSMS and come back to gui, or you build complex UI (aka rebuild SSMS).
At the end of day, if you want bazillion reports for gazillion different users, you have to pay for it. I see too many "architectural astronauts" who exposes application to accept SQL statements only to make everyone waste time guessing what should be put into it. No cost saving at all.
Ok, if you must do that, well eh... Good luck. Best bet is to return as a DataTable and dump the rows/columns/data on to the view with nested foreach looping through rows then columns.
I'm working with a (.net4 / mvc3 ) solution file downloaded (from a reputable source) where a connection string exists in web.config but I don't see explicit instructions to create the database and there's no included '.mdf'. The first time I build I got a runtime error regarding lack of permissions to CREATE database. So I created a blank db and made sure the string referenced a SQL user that had .dbo/owner rights to the db just created.
But subsequent builds don't seem to execute that same initialize db script - where ever that's stored.
Where is this 'first use' convention for creating databases documented?
thx
That is a feature of Entity Framework Code First. I am not sure what you are looking for exactly, but searching for "EF Code First Initialization Strategy" might help.
For instance read this article: EF Code First DB Initialization Using Web.Config
I assume you are talking about Entity Framework, which allows you to create the database from an instance of an ObjectContext object, which is used in any of the three approaches in EF (database-, model- and code-first).
Look for a line that actually calls ObjectContext.CreateDatabase(). If one of the supported ADO.NET provides is used (SQL Server or SQL Server CE 4.0) this will generate the required SQL Statements. Assuming the classic Northwind example, you might find something like that:
NorthwindContext context = new NorthwindContext();
if (!context.DatabaseExists())
{
context.CreateDatabase();
}
If this is in fact a code-first application, "lalibi" is right about the initialization strategy which by default doesn't require you to explicitly create the database. (But my guess is, that it actually uses a statement internally very similar to mine).
I am experiencing some bizarre problems with Nhibernate within my MVC web application.
There is not 1 consistent error, I keep getting loads of random ones:
Transaction not successfully started
New request is not allowed to start because it should come with valid transaction descriptor
Unexpected row count: -1; expected: 1
To give a little context to the setup, I am using Ninject to DI the sessions and other Nhibernate related objects, currently I am using RequestScope however I have tried SingletonScope. I have a large and complicated data model, which is read out as a whole, but persisted back in separate parts, as these can all be edited and saved individually.
An example would be having a Customer object, which contains a address object, a contact object, friends object, previous orders object etc etc...
So the whole object is read out, then mapped to the UI domain models and then displayed in different partials within the page. Each partial can be updated individually via ajax, so you may update 1 section or you could update them all together. It seems mainly to give me the problems when I try to persist them all together (so 2-4 simultanious ajax requests to persist chunks of the model).
Now I have integration tests that work fine, which just test the persistence and retrieval of entities. As a whole and individually and all pass fine, however in the web app they just seem to keep throwing random exceptions, and originally refused to persist outside of the Nhibernate cache. I found a way round this by wrapping most units of work within transactions, which got the data persisting but started adding new errors to the mix.
Originally I was thinking of just scrapping Nhibernate from the project, as although I really want its persistance/caching layer, it just didnt seem to be flexible enough for my domain, which seems odd as I have used it before without much problem, although it doesn't like 1-1 mappings.
So has anyone else had flakey transaction/nhibernate issues like this within an ASP MVC app... I know this may be a bit vague as the errors dont point to one thing, and it doesn't always error, so its like stabbing in the dark, but I am out of ideas so any help would be great!
-- Update --
I cannot post all relevant code as the project is huge, but the transaction bit looks like:
using (var transaction = sessionManager.Session.BeginTransaction(IsolationLevel.ReadUncommitted))
{
try
{
// Do unit of work
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
Some of the main problems I have had on this project have stemmed from:
There are some 1-1 relationships with composite keys, but logically it makes sense
The Nhibernate domain entities go through a mapping layer to become the UI domain entities, then vice versa when saving. Problem here is that with the 1-1 mappings, when persisting the example Address I have to make a Surrogate Customer object with the correct Id then merge.
There is ALOT of Ajax that deals with chunks of the overall model (I talk like there is one single model, but there are quite a few top level models, just one that is most important)
Some notes that may help. I use windsor but imagine the concepts are the same. Sounds like there may be a combination of things.
SessionFactory should be created as singleton and session should be per web request. Something like:
Bind<ISessionFactory>()
.ToProvider<SessionFactoryBuilder>()
.InSingletonScope();
Bind<ISession>()
.ToMethod( context => context.Kernel.Get<ISessionFactory>().OpenSession() )
.InRequestScope();
Be careful of keeping transactions open for too long, keep them as short lived as possible to avoid deadlocks.
Check your queries are running as as expected by using a tool like NHProf. Often people load up too much of the graph which impacts performance and can create deadlocks.
Check your mappings for things like not.lazyload() and see if you actually need the additional data in the queries and keep results returned to a min. Check your queries execution plans and ensure adequate indexes are in place.
I have had issues with mvc3 action filters being cached, which meant transactions were not always started, but would attempt to be closed causing issues. Moved all my transaction commits into ActionResults in the controllers to keep transaction as short as possible and close to the action.
Check your cascades in your mappings and keep the updates to a minimum.
Using asp.net MVC in c#, I am making a call to a stored procedure using Linq into my SQL Members table. I have no internal caching on the application, already checked to make sure it is turned off.
Test case:
I have my username set to test1. From the website I change my username to test2. The website still shows test1. I go to Management Studio and run my stored procedure called MemberByEmail, it shows test2 correctly.
I start simple, refresh my page to see if it's browser cache, still test1. I go to debugging and walk through the code and find that it goes correctly all the way to here to call the database:
/// <summary>Method that is mapped to the dbo.MemberByEmail database procedure.</summary>
/// <returns></returns>
[System.Data.Linq.Mapping.Function(Name="dbo.MemberByEmail")]
public System.Data.Linq.ISingleResult<BookCrossing.Data.Member> MemberByEmail(
[System.Data.Linq.Mapping.Parameter(DbType="nvarchar(100)")] string email)
{
var methodInfo = (System.Reflection.MethodInfo)System.Reflection.MethodInfo.GetCurrentMethod();
var result = this.ExecuteMethodCall(this, methodInfo, email);
return ((System.Data.Linq.ISingleResult<BookCrossing.Data.Member>)(result.ReturnValue));
}
I turned on the profiler for my sql db, and it actually shows an entry for MemberByEmail, and the result set that came back had username = test1 .
Again I ran the stored procedure through Management Studio, and it came up with test2 as the username. I waited for 15 minutes, refreshing the web page every 5 or so, and it never cleared and served the correct test2 from the db. The last strange piece, I ran IISReset and refreshed the page, test2 was returned.
I'm guessing this I am just overlooking something obvious. Any help or advice would be great. Thanks
UPDATE: I created a console application to take out the web piece of it. The problem is the same when accessing directly from a console app also, no change.
How are you calling this from the webpage? If via an Ajax call, IE helpfully caches the result for you...
Took a while but we got this resolved. Data access is done through a MemberRepository in our project, and we loaded member repository in our MembershipProvider class. The problem is that the MembershipProvider class was loaded at the start of the application and never removed, so all MemberRepository calls were done through the same context. The strange part is that the call went all the way to SQL (as noted we were able to see the request in profiler), but the bowels of the code got back the results set but instead used the first calls result set and sent that back to us.
So by moving the Repository into the desired method or our MembershipProvider, it was destroyed after each call and that solved the issue. I don't know that this is specific to our set up, but hopefully it will help someone in the future.