Can we use SQLMetal Objectmodel as application object model? - c#

Our team has just started using Sql Metal and I have been playing around with it for 2 days. While doing this, I have noticed couple of things.
When we run command like following
sqlmetal /code:ps.cs /server:devapp042dbs
/database:promotionalsponsorship /namespace:DAL
It creates a "LINQ to SQL SQLMEtal" object model. Now, this is not our regular class. It has a lot of autogenerated code and it almost smells like LINQ/EF with a lot of autogenerated properties and methods.
I have used Micro ORMs like Dapper and ORMLite from Service stack and the onderful thing about those is that it works with the simple objectmodel that we have created rather than auto-generating its own object model.
My question is that can we use these SQLMetal mapping classes as our Models of the application or we have to create a simple wrapper class around it using which we can extract all the information that we need to.
To clarify my point following are the samples of what I call a SQL Metal Class and a simple model class

Although this question would possibly be closed, as the answer is subjective, the short answer is yes, it is perfectly valid to use such autogenerated set of classes as your model. There are plenty of succesful apps built this way.
Since these classes are partial, you can even extend your domain model by adding custom properties/methods/events.
If you are concerned that the autogenerated code is not clean enough, consider the code first approach of the Entity Framework, nHibernate or any other ORM that supports this scenario. This way you start from a clean POCO model and just define its mapping to a relational structure.

Related

entity framework clarification about model objects and their methods

I had a conceptual question about EF.
I am pretty new to the idea of an ORM in general, so I wanted to get some clarification on somethings:
I have an existing database, and I want to convert the data I am pulling from that data into objects that my application can interact with as objects, rather than just data.
An ORM will accomplish that, correct?
In EF can I create methods specific to my objects? For instance, can I make it so my application can call something like employee.ViewDetails() Where employee is an object?
If so, is there a simple tutorial you could recommend?
Is EF portable between applications? Meaning, is it easy to build an EF structure and then port it to multiple applications?
I can just do that by referencing it from different solutions, no?
Thanks for all the help
Before Answering your Question let me give you short brief about Entity Framework
Using the Entity Framework to write data-oriented applications provides the following benefits:
Reduced development time: the framework provides the core data access capabilities so developers can concentrate on application logic.
Developers can work in terms of a more application-centric object model, including types with inheritance, complex members, and relationships. In .NET Framework 4, the Entity Framework also supports Persistence Ignorance through Plain Old CLR Objects (POCO) entities.
Applications are freed from hard-coded dependencies on a particular data engine or storage schema by supporting a conceptual model that is independent of the physical/storage model.
Mappings between the object model and the storage-specific schema can change without changing the application code.
Language-Integrated Query support (called LINQ to Entities) provides IntelliSense and compile-time syntax validation for writing queries against a conceptual model.
Going Back to your first Question
Yes
Entity framework is useful in three scenarios.
1- First, if you already have existing database or you want to design your database ahead of other parts of the application. (Which is your current case)
2- Second, you want to focus on your domain classes and then create the database from your domain classes.
3- Third, you want to design your database schema on the visual designer and then create the database and classes.
2) in EF can I create methods specific to my objects? For instance, can I make it so my application can call something like employee.ViewDetails() where an employee is an object? If so, is there a simple tutorial you could recommend?
Yes Sure Take a look on this:
- https://msdn.microsoft.com/en-us/library/dd456847.aspx
- http://www.asp.net/mvc/overview/older-versions-1/models-data/creating-model-classes-with-the-entity-framework-cs
3) Is EF portable between applications? Meaning, is it easy to build an EF structure and then port it to multiple applications? I can just do that by referencing it from different solutions?
you might need to Implementing the Repository Patterns
Have a look at this Amazing tutorial
http://blog.gauffin.org/2013/01/repository-pattern-done-right/
http://rycole.com/2014/01/25/entity-framework-repository-pattern.html
Hope this helps!
Wish you the best :)
Blubberbo,
There are various ways to work with EF, they are Code First, Model First and Database first.
More information can be found in the below SO post.
Code-first vs Model/Database-first
1) You can use LINQ to SQL or LINQ Objects in context with an ORM like EF to interact with Objects.
2) If you would like methods specific to specific types, then you might want to take a look at writing extension methods for specific types.
More information here
https://msdn.microsoft.com/en-us/library/bb311042.aspx
3) To make it portable, you might want to build abstractions around it, like for example you might want to write repository classes to separate the DB layer that uses EF and the layer that calls it(a.k.a the repository layer).
More info can be found here
http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
Hope that helps,
Praveen Raju

Entity Framework understanding [duplicate]

This question already has an answer here:
ORM Entities vs. Domain Entities under Entity Framework 6.0
(1 answer)
Closed 7 years ago.
I start using Entity Framework about a year ago using Database-First approach. While reading and doing research online, I came across some terminologies that are confusing me. I was wondering if someone can help clear up some questions I have:
1) Using Database-First approach, I build my SQL Tables and create my edmx file from the database. From there, I start coding by create a Data Context and then accessing the entities. I recently read and see that I can right click in the .edmx file and "Add Code Generation Item" and then add "Ado.Net EntityObject Generator/EF 5.x DBContext Generator/EF4.x POCO Entity and etc. What is the purpose of these different code Generators? Am I suppose to implement them? When should I implement them?
2) I'm reading a lot about "object model and domain model". Is EF an object model or domain model ORM?
Thank you in advance for any information.
Add Code Generation Item
By default classes are generated with the help of EntityModelCodeGenerator. With the help of custom code generation, you can customize this. Why you would want to do ?
One example I could give from top of my head is - if you want to implement INotifyPropertyChanged interface by every single entity generated by EDMX. By default EntityModelCodeGenerator would not do that for you. Thus, you would want to customize this.
(Please note this is just my theoretical knowledge however the above example is quite a practical situation)
Domain Model vs Object Model.
Regardless the difference one thing for sure is Domain Model is Object Model too because in both cases you are defining classes, and association. This is how I define Domain Model and Object Model.
The only major difference could be how you are defining objects; in case of Domain Model, you are completely thinking from Business point of view and defining your objects.
From what I see that it is probably EF Database first is Object Model because when I am doing Database designing I am less thinking about Business, rather I am thinking about what is to be stored.
If am making POCO then I probably will be thinking from Domain Model point of view.
In case of EF - Code First, I have started thinking from Business point of view and make my association, then after I think of how objects will be stored.
So it is just a perception and at the end whether Domain Model or Object Model, ORM i.e. EF will provide you to persist this object into the database.
I hope it helps.
You don't normally need to use the "Code Generation Item" option. It is used to perform changes in the version of EF being used, and you could use it to do some custom code generation. In general, you should be able to leave this option alone.
EF is really an ORM (Obect-Relational Mapper). It takes objects and maps them to relations (tables). It can be used as either an object model or domain model (or both) as well depending on how you define those terms.

EntityFramework (ORM) object names and domain model names - how to avoid duplicates?

Let's say I have a project where I use Entity Framework, but I want to use my own classes instead of the EF classes.
Reasons for using my own classes:
Easy to add properties in code
Easy to derive and inherit
Less binding to the database
Now, my database has table names like User and Conference.
However, In my domain project, I also call my files User.cs and Conference.cs.
That means I suddenly have two objects with the same naming, which is usually very annoying to work with, because you have to use namespaces all the time to know the difference.
My question is how to solve this problem?
My ideas:
Prefix all database tables with 'db'. I usually do this, but in this case, I cannot change the database
Prefix or postfix all C# classes with "Poco" or something similar
I just don't like any of my ideas.
How do you usually do this?
It's difficult to tell without more background but it sounds like you are using the Entity Framework designer to generate EF classes. This is known as the "Model First" workflow. Have you considered using the Code First / Code Only workflow? When doing code first you can have POCO classes that have no knowledge of the database, EF, or data annotations. The mapping between the database and your POCOs can be done externally in the the DBContext or in EntityTypeConfiguration classes.
You should be able to achieve your goal of decoupling from EF with just one set of objects via code first.
To extend the above answer, the database table name User (or Users as many DB designers prefer) is the identifier for the persistence store for the object User that's defined in your code file User.cs. None of these identifiers share the same space, so there should be no confusion. Indeed, they are named similarly to create a loose coupling across spaces (data store, code, development environment) so you can maintain sanity and others can read your code.

How to save changes with Breeze without EF?

I'm working with repositories and one thing I'm really working hard on is to make things as most decoupled as they can. So, if tomorrow we change from relational databases to something else, like NoSQL and things like that we are good to go, we just have to change our DAL.
I've been trying to find out how to implement the SaveChanges method in my WebAPI controller without needing to use the EFContextProvider. I've found then the Breeze NoDb sample, however this sample uses the Breeze ContextProvider in the repository. This is something that troubles me because Breeze is a JS library, so it is something about the presentation of my application. In that case, making the repository use a component from Breeze will couple the DAL and the presentation, something I don't want to do.
Searching again for how to implement SaveChanges without EF I've found this question where there's one very good answer telling how to convert the SaveBundle to a SaveMap and then tell to use this to implement the saving logic. However I'm stuck in this method because the entries of the SaveMap give just one Type object and the EntityInfo, so I don't see how to use this with my repositories.
So, how to deal with SaveChanges without to refer to EFContextProvider and without coupling the repositories with the ContextProvider?
Are you planning to switch from SQL Server to NoSQL database? why don't you want to do that just now? How often are you planning to switch backing storage? Probably not often, if ever.
I found that database switch, especially from SQL to NoSQL is a big shift in paradigm. In one of my application I've gone through conversion from SQL to RavenDb. Despite of having everything decoupled and with using Repositories everywhere, I still had to rewrite most of the application storage logic.
What you are trying to do - you are not going to need it. So stop making life hard for yourself and get on with implementing features.
The ContextProvider does the work of converting the JObject (which Json.NET gives you in the SaveChanges method), into real, typed .NET objects. The EntityInfo object that the ContextProvider creates for each entity contains the entity object itself, as well as the entityAspect properties that it got from the client: the EntityState (Added, Modified, or Deleted), the original values of all changed properties, and the temporary values for any auto-generated keys. This is the information that you would need to save the entities yourself. The "SaveMap" just organizes them by Type for convenience, but you can manipulate them however you like.
As described in the post you referenced, you could proceed by using a ContextProvider just to convert the JObject to entities, then pass those entities to the appropriate repositories. Your repositories don't need to know anything about the ContextProvider.
Breeze offers an NHibernate provider that you can look at that shows how to talk to a non EF backend that is still a .NET server. The ContextProvider is a convenence that makes implementing any .NET provider substantially easier, but it is by no means a requirement.
As for NoSQL you should take a look at the breeze Node provider and MongoDB sample which is hosted in NodeJs ( which shows that the ContextProvider is obviously not a requirement).
We also expect to have a Breeze server implementation written in Java in the near future, which again has no "ContextProvider" requirement.

How to avoid declaring database fields twice, once in database, once in a repository/model?

I recently began reading Pro ASP.NET MVC Framework.
The author talks about creating repositories, and using interfaces to set up quick automated tests, which sounds awesome.
But it carries the problem of having to declare yourself all the fields for each table in the database twice: once in the actual database, and once in the C# code, instead of auto-generating the C# data access classes with an ORM.
I do understand that this is a great practice, and enables TDD which also looks awesome. But my question is:
Isn't there any workaround having to declare fields twice: both in the database and the C# code? Can't I use something that auto-generates the C# code but still allows me to do TDD without having to manually create all the business logic in C# and creating a repository (and a fake one too) for each table?
I understand what you mean: most of the POCO classes that you're declaring to have retrieved by repositories look a whole lot like the classes that get auto-generated by your ORM framework. It is tempting, therefore, to reuse those data-access classes as if they were business objects.
But in my experience, it is rare for the data I need in a piece of business logic to be exactly like the data-access classes. Usually I either need some specific subset of data from a data object, or some combination of data produced by joining a few data objects together. If I'm willing to spend another two minutes actually constructing the POCO that I have in mind, and creating an interface to represent the repository methods I plan to use, I find that the code ends up being much easier to refactor when I need to change business logic.
If you use Entity Framework 4, you can generate POCO object automatically from the database. ( Link)
Then you can implement a generic IRepository and its generic SqlRepository, this will allow you to have a repository for all your objects. This is explained here : http://msdn.microsoft.com/en-us/ff714955.aspx
This is a clean way to achieve what you want: you only declare your object once in your database, generate them automatically, and can easily access them with your repository (in addition you can do IoC and unit test :) )
I recommend you to read the second edition of this book which is pure gold and updated with the new features introduced in MVC 2
http://www.amazon.com/ASP-NET-Framework-Second-Experts-Voice/dp/1430228865/ref=sr_1_1?s=books&ie=UTF8&qid=1289851862&sr=1-1
And you should also read about the new features introduced in MVC3 which is now in RC (there is a new view engine really useful) http://weblogs.asp.net/scottgu/archive/2010/11/09/announcing-the-asp-net-mvc-3-release-candidate.aspx
You are not declaring the business logic twice. It's just that this business logic is abstracted behind an interface and in the implementation of this interface you can do whatever you want : hit the database, read from the filesystem, aggregate information from web addresses, ... This interface allows weaker coupling between the controller and the implementation of the repository and among other simplifies TDD. Think of it as a contract between the controller and the business.

Categories

Resources