What are the advantages/disadvantages of using DB First versus Code First? - entity-framework

I know enums are currently only available in the June 2011 CTP and won't be in 4.2. What other factors would make someone choose one or the other?

Ladislav Mrnka has a great SO answer that breaks down the differences between DB First, Code First and Model First. I strongly suggest that you go read it and upvote it.
Besides that, I would only add the following points:
Even in the June 2011 CTP, Enum support is limited, so you might
want to see if any of those issues are showstoppers for you. Update: EF5+ supports Enums with EF Designer and Code First.
If you are implementing EF against an Oracle DB, and you
don't want to pay for a data provider, then you will be
without Code First, as Oracle's own provider (still in beta)
doesn't support it.
Edit: here is another comprehensive answer from Ladislav.

See Entity Framework Development Approaches in
http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

Advantages : One common syntax ( LINQ / Yoda ) for all object queries whether it is database or not , Pretty fast if used as intended , easy to implement SoC , less coding required to accomplish complex tasks
Disadvantages : you have to think in a non traditional way of handling data , not available for every database
Disadvantage: If there is any schema change in database FE won’t work!!! You have to update the schema in solution as well!!!
Advantage: Its fast and straight forward using LINQ/FE objects For Add/Modify/Delete/Update.
Advantages:-Easy to map business objects (with drag & drop tables on environment).
-It keeps a good performance when you work with a small / middle domain model.
Disadvantages:-It's limited when you work with a huge domain model.
-Scalability.

Related

How do we switch from Telerik Open Access to anything else?

Our company has been using Telerik Open Access for years. We have multiple projects using it including some in development and some in production that need updated. Because Telerik no longer updates or supports Open Access, we are having a variety of problems. We've got users that have to go to another work station because we can't get Open Access on their computers and we've got projects where we can't add or update tables because the visual designer doesn't work in modern Visual Studio versions. So my question is, how do we convert these and what do we convert these to?
I've heard of Microsoft Entities Framework and we used to just call stored procedures instead of having a separate data project. Obviously our clients aren't going to pay us for hours to switch so we need something that works quick. How do we convert our existing Telerik Open Access project to Microsoft Entities Framework, straight SQL queries, or some other data layer option?
Here's an example of what we have currently.
A separate Visual Studio project that acts as our data layer where all the code was created by Telerik Open Access's visual designer:
We then have a DataAccess.cs class in our main project that creates the instance of the data layer:
Then we call it by using linq statements in the main project:
I don't know OA hands-on, so I can only put my two-cents in.
I'm afraid this isn't going to be be an easy transition. I've yet to see the first seamless transition from one data layer implementation to another (and I've seen a few). The main cause for this is that IQueryable is a leaky abstraction. That is, the data layer exposes IQueryables, but
it doesn't support all features of the interface, and
it adds its own features, and
it's got its own interpretation of how to implement the features that are supported.
This means that if you're going to port your data layer to EF, you may notice that some LINQ queries throw runtime errors because they contain unsupported .Net methods/properties (for instance DateTime.Date), or perform worse -- or better, or return data in subtly different shapes or sorting orders.
Some important OA features that are missing in EF:
Runtime mappings (EF's mapping is static)
Bulk update/delete functions (with EF: only by using third-party libraries)
Second-leve cache
Profiler and Tuning Advisor
Streaming of large objects
Mixing database-side and client-side evaluation of LINQ queries (EF6: only db-evaluation)
On the other hand, the basic architectures of OA and EF don't seem to be too different. They both -
support POCOs
work with simple navigation properties
have a fluent mapping API
support LINQ through IQueryable<T>, where T is an entity class.
most importantly: both have revolve around the Unit of Work and Repository patterns. (For EF: DbContext and DbSet, respectively)
All-in-all it's goinig to be a delicate process of converting, trying and testing. One good thing is that your current DAL is already abstracted to a certain extent. Another is that the syntax doesn't even look too different. Where you have ...
dbContext.Add(newDockReport);
dbContext.SaveChanges();
... using EF this would become ...
dbContext.DockReports.Add(newDockReport);
dbContext.SaveChanges();
With EF-core it wouldn't even have to change one bit.
But that's another important choice to make: EF6 or EF-core? EF6 is stable, mature, feature-rich, but at the end of its life cycle (a phrase you've probably come to hate by now). EF-core, on the other hand, is the future, but is presently struggling to get bug-free in its major functions, not yet as feature-rich as EF6 (and some features will never return, although other new features are great improvements compared to EF6). At the moment, I'd be wary of using EF-core for enterprise applications, but I'm pretty sure that a year from now this is not an issue any more.
Whichever way you go, I'd start the process by writing large amounts of integration tests, if you didn't do so already. The advantage of integration tests is that you can avoid the hassle of mocking either framework first (which isn't trivial).
I have never heard of a tool that can do that.Expect it to take time.
You have to figure how to do it by yourself :
( for the exact safer way to migrate )
1rst you must have a simple page that use your DataLayer it will be your test page. A simple one that you can adapt the LinQ logic .
Add a LinQ to SQL Class, Right click> Add > LinQ to SQL Class.
Drop your table for this page only the usefull one, put the link if needed.
In the test page create a new data context of the linQtoSql.
Use it fixing the type and rename what have to be rename.
Fix error till it compile.
Stock coffee and anything that can boost your brain.
Add table to your context to match the one you had in telerik data access.
Debug for days.
Come back with new question on how to fix a new issue twice a day.
To help with the dbContext.Add() difference between the 2 frameworks you could use this extension in the EF 6.x :
public static void Add<T>(this DbContext db, T entityToCreate) where T : class
{
db.Set<T>().Add(entityToCreate);
db.SaveChanges();
}
then you could do :
db.Add(obj);
See Gert Arnold answer : In Entity Framework, how do I add a generic entity to its corresponding DbSet without a switch statement that enumerates all the possible DbSets?

F# mapping data entities to domain entities; what is meant by "using objects for persistance"?

In my spare time, I'm trying restart my effort to learn F#. I'm doing so by trying to create a simple application that will allow me to analyze my financial transactions.
My first attempt at creating this application failed due to the persistence step. I used SQL and the EntityFramework package, but the latter generated database entities, which I did not want to use throughout my application since they're all mutable (I think..). Instead I had to map these database entities to domain entities. Much manual glue code later it worked....until I found a bug and was forced to replace much of that glue code. That was the tipping point that made me quit.
On SO I found a question describing my situation, e.g. Saving F# types to a database. Mark Seeman suggested that the pain of mapping can be overcome if I'd not use objects for persistence. At work I have recently been introduced to MongoDb, which at least saves me the pain of mapping from database entities to domain entities. These entities all need some ID, and I chose to use an ObjectId from Mongo. Ooops, there comes the deja vu, in order not to have my domain entities being dependent on Mongo, I will once more have to create database and domain entities....as well as the mapping. Bah & Ugh.
In C# I'm used to do such mapping with tools like Automapper, but they don't really work for special F# types. So now I'm wondering what Mark Seeman ment by "using objects for persistance". How is this solved in F#? So far I haven't been able to fine more info on this topic besides the aforementioned question on SO.

Conceptual questions on the ASP.NET MVC 3 and Entity Framework/MySQL interface

I have now decided to try out ASP.NET MVC 3.
My host provider, however, only supports MySQL and therefore I have to figure out how to use MVC 3 with MySQL.
I have also decided that I don't wanna do any SQL code if I can avoid it, and I would also like O/RM without too much effort. I understand that the Entity Framework will actually help me accomplish this to a large extent.
I have been trying to get into the various ways of using the EF, with the database first, model first and code first approaches supplied by the framework.
So far, I have not had much luck, and I find that the examples available all use very different approaches that confuses me a lot.
I might begin by asking for guidance on getting a few concepts right.
First of all, the Model (in MVC) is actually more like a ViewModel, that represents something (Users, Posts, etc.) in terms of Properties is more or less simple classes. I.e. the model is where the data from the database gets mapped to an object (the O/RM). Am I right?
A repository is a wrapper that encapsulates a specific way of retrieving data for the models. For instance, a DatabaseRepository or a FakeTestRepository.
Should I have a single repository in my MVC project, or a repository per database table, such that I have a UsersRepository and PostsRepository?
Should the repository be a model for itself, not a model at all, or tied to individual models (so that UsersRepository is part of the UsersModel)?
I have tried to use the EF's model first approach, and for a simple test I just have created an empty model and added the entities "Author" and "Guide" that are related by a one-to-many relation.
When I then, in Visual Studio 2010, "Generate database from model", I get the corresponding sql code. I want this database to be created in MySQL. How can I accomplish that?
Are there some code examples for MVC 3 with MySQL and O/RM where the creation of a small site is demonstrated?
Thanks.
Concerning EF Model First approach: take a look at this Tips & Tricks article. We have described this common situation in it (it is Oracle-specific, but dotConnect for MySQL contains the "Devart SSDLToMySQL.tt" template).
As for the rest of the questions - there is no definite answer. Choose the approach that suits you better.
In my point of view, you should try the code first. And as you said that your host only provides MySQL you can also use MySQL database as a database I personally use MySQL. Concepts are the same but logic is different you have to code it a different way. But from my point of view, you can use MySQL as a database service.

How do I create a stored procedure with Entity Framework?

I read an old MSDN Forums post about Entity Framework where Julie Lerman stated:
wrt Stored Procedures. This is even
better than what you are referring to.
Not only can you map to sprocs (both
in EF and in LINQ to SQL) or override
the update/insert/delete methods, but
in EF, there is coming a capability to
CREATE stored procedures right in the
mapping layer. Not create them and add
them into the db, but just have them
live in the EDM. So the sproc doesn't
have to exist in the db.
This is not in the March bits, but I
saw a demo of it last week and we will
have it in the next CTP.
I want to see a demo of how this works, but it is excruciatingly hard to jump into such a huge framework and all of its documentation, and discover how to look at a single feature. From best as I can tell, Entity Framework is not dynamic enough to support the scenarios I want, at least not yet, but there are features discussed for future versions of EF that fit my needs. For now I am using a hand-rolled query generator, since the ORM features of EF do not fit my needs and I really just want an awesome query generator and the ability to create stored procedures and serialize Parameterized Queries.
Bottom line: So how does Entity Framework create stored procedures "live" without them existing a priori in the database? Is it customizable? How does it handle changes to the conceptual layer? And why would the mapping layer own this logic? Or is Julie just referring to something gross like T4 Templates (YUCK!!!)?
Julie's post seems a little vague. If it's not in the DB, it's not a "stored proc" as most people know it. I don't think she meant generate a proc; I don't think you can do that today, and I know you couldn't do it in 2007. Nor was T4 in use in 2007.
She may have been talking about EdmFunction, but it's hard to tell. She's pretty active on Twitter, so you could just ask her what she meant.

Rules of thumbs for writing "queries" using ADO.NET Entity Framework

I’m currently working on a prototype of a medium size web application, and I thought that it would be good to also experiment with Entity Framework. The problem is that the major part of the application is not the data layer and logic, and so that I don't have much time to play with Entity Framework. On the other hand, the database schema is quite simple.
One of the problems I’m facing is that I cannot find a consistent way to "write queries". As far as I can tell, there are four "interfaces" for the job:
LINQ to Entities
LINQ to Entities using LINQ extension methods
Entity SQL
Query builder
OK, the first two are essentially the same, but it’s good to use just one for maintenance and consistency.
I’m mostly puzzled by the fact that none of them seems to be complete and the most general. I often find myself cornered and using some ugly looking combination of several of them. My guess is that Entity SQL is the most general one, but writing queries using strings feels like a step back. The main reason I’m experimenting with something like Entity Framework is that I like the compile time checking.
Some other random thought / issues:
I often also use the ObjectQuery.Include() method, but again it takes a string. Is this the only way?
When to use ObjectQuery.Execute() (vs. ToList())? Does it actually execute the query?
Should execute queries as soon as possible (e.g. using ToList()) or should I not care just let leave the execution for the first enumeration which gets in the way?
Are ObjectQuery.Skip() and ObjectQuery.Take() available only as extension methods? Is there a better way to do paging? It’s 2009 and almost every web application deals with paging.
Overall, I understand there are many difficulties when implementing an ORM, and often one has to compromise. On the other hand, the direct database access (e.g. ADO.NET) is plain and simple and has well defined interface (tabular results, data readers), so all code - no matter who and when writes it - is consistent. I don’t want to faced with too many choices whenever writing a database query. It’s too tedious and more than likely different developers will come up with different ways.
What are your rules of thumbs?
I use LINQ-to-Entities as much as possible. I also try and formalise to the lambda-form, as opposed to the extended SQL-style syntax. I have to admit to have had problems enforcing relationships and making compromises on efficiency just to expedite my coding of our application (eg. Master->Child tables may need to be manually loaded) but all in all, EF is a good product.
I do use EF's .Include() method for lazy-loading, which as you say, does require a string input. I find no problem with this, other than that of identifying the string to use which is relatively simple. I guess if you're keen on compile-time checking of such relations, a model similar to: Parent.GetChildren() might be more appropriate.
My application does require some "dynamic" queries to be performed, though. I have two ways of meeting this:
a) I create a mediator object, eg. ClientSearchMediator, which "knows" how to search for clients by name, etc. I can then put this through a SearchHandler.Search(ISearchMediator[] mediators) call (for example). This can be used to target specific data structures and sort results accordingly using LINQ-to-Entities.
b) For a looser experience, possibly as a result of a user designing their own query (using high level tools our application provides), eSQL is ideal for this purpose. It can be made to be injection-safe.
I don't have enough knowledge to address all of this, but I'll at least take a few stabs.
I don't know why you think ADO.NET is more consistent than Entity Framework. There are many different ways to use ADO.NET and I've definitely seen inconsistency within a single code base.
Entity Framework is currently a 1.0 release and it suffers from many 1.0 type problems (incomplete & inconsistent API, missing features, etc.).
In regards to Include, I assume you are referring to eager loading. Multiple people (outside of Microsoft) have developed solutions for getting "type safe" includes (try googling something like: Entity Framework ObjectQueryExtension Include). That said, Include is more of a hint than anything. You can't force eager loading and you have to always remember to call the IsLoaded() method to see if your request was fulfilled. As far as I know, the way "Include" works is not changing at all in the next version of Entity Framework (4.0 - to ship with VS 2010).
As far as executing the Linq query as soon as it's built vs. the last possible moment, that decision is situational. Personally, I would probably execute it as soon as it's built for the most part unless there was a compelling reason not to, but I can see other people going the opposite direction.
There are more mature ORMs on the market and Entity Framework isn't necessarily your best option. For the most part, you can bend Entity Framework to your will, but you may end up rolling your own implementation of features that come out of the box with other ORMs.