orm with entity framework 4 and code first - c#

I want to write a library to store any objects to a database. I still did the mapping for known objects using code first and the classes DbContext and DbSet. But in this case I don't know the structure of the objects I have to map. Is there a way to do this with the classes above?

The only way you could do it is to create mapping classes dynamically and loading them into the ORM, but I'm not sure this is possible with EF4 since I'm a NHibernate guy.
By the way, I can't see a motive behind this. Why would you need such a thing?
If you need to store objects that have different (and unknown) schema you can use the Serialized LoB pattern (http://martinfowler.com/eaaCatalog/serializedLOB.html) using a TEXT field in a relational database or go schema less with a NoSql document database such as MongoDB.

Related

Is Entity Framework capable of interacting with other databases with unknown table structures?

I have been using EF for my latest project and have enjoyed the ease of programming with it. Although it is slightly harder to setup and uses its own rules on connections, but once in place, treating your database the same as you classes and their methods adds a great layer of simplicity to it.
However, in my case I encountered occasions with which I am still not able to use EF. My program has a main database to work with. That is fine! But it also communicates with other databases on the same server. E.g. it reads data from an outside table that the user specifies inside the program. Those tables are of course not recognized by EF and they have different structures every time. To communicate with those tables I have to resort to normal Sql codes as before. So I feel a little bit between the two worlds.
I am just wondering if it is possible for foreign data to dynamically become part of the Entity Model or whether this foreign data can be accommodated in the framework?
As I know, it's impossible. Entity Framework is ORM, so it maps your Model (classe) to database. So if you don't know your Model you can't tell EF how to map it. You should use another approach to communicate with dynamic data.
Give LINQ-to-SQL (L2S) a try; I think you'll find, a lot of what you like about EF is the expressiveness of LINQ-to-Entities (L2E), and the LINQ syntax is the same.
I won't lie to you, though: there does always come a time using L2S where I wished my relations were first class properties on a POCO, but you can't have everything in this situation.

Data Access Framework that addresses my needs

I'm having trouble choosing an appropriate data access framework, partly because I'm very picky with my preferences and mostly because I don't have much experience with most of them :-)
I need a framework that will allow me to easily map between the DB tables (SQL Server) and my entities, and that will handle the CRUD operations for me (for the most part).
I want my entities to reside in a separate assembly from my DAL.
I prefer using attributes for the mappings over external file like XML.
It doesn't have to be an ORM, and I want to code my entities myself.
I don't mind writing stored procedures.
The project's database won't be very big. Less than 50 tables.
I'd like some of my entities to correspond to an inner join of two tables - one for static data entered manually during development and the other with data filled during runtime - without using two entities that reference one another (the result of this join will be a single entity).
Entity Framework sounded perfect until I realized it doesn't support Enums (yet - and I can't wait for EF 5.0).
I want these entities to include Enums, and plan on using lookup tables for the enums + code generation for the enum to keep it synchronized with the database.
Linq-to-SQL seems like a good candidate, but I don't know if it copes well with my previous demands.
Using Enterprise Library 5.0 DAAB with it's RowMapper, and extending it's abilities to perform updates and inserts is also an option (but will require more coding on my part).
I plan on implementing the Repository Pattern.
How about NHibernate? Would it do? No experience there either.
I would be happy to hear all suggestions.. the more the merrier! Thanks in advance!
I think nHibernate is the way to go, although some of its main strengths (ORM, stored procedure generation, etc) are things you listed as non-requirements. Anyway, nHibernate will do everything you want it to do. Technically it does use xml mappings, but these can easily be auto-generated using fluent attribute mapping. I like this, as it IS done for you, but you get the customization too just in case you need it. Good luck!

How to create my DDD entities with Mongodb/Couchdb?

I am starting my first project using DDD (using C#) and at this stage I feel we will probably go with MongoDB or maybe CouchDB for the persistence (an ORM like Entity framework seems too much of an overkill for what we want), but saying that I have pretty much zero experience in MongoDB or CouchDB at this stage.
As I am creating my domain I thought about using GUIDS as my IDs for my entities (coming from a relational database world, still having trouble moving away from it).
If I go down this route will I be able to easily plugin in my persistence layer (mongoDB/CouchDB) or would I have to change my domain model (currently my constructors on my entity objects have a string ID as a parameter (which will be the GUID ID)).
JD
With MongoDB you probbly want to have a collection per aggregate root, which means that your aggregate roots needs ids, since they will be the documents in the DB. If you want to keep your domain model free of MongoDB specific code those ids can be strings.
I would not include the ids in the constructor arguments. I would just let them be writable properties. As with an ORM I would consider handling reading and storing of entities via repositories. And keep the MongoDB code in there.

Strategies for replacing legacy data layer with Entity framework and POCO classes

We are using .net C# 4.0, VS 2010, EF 4.1 and legacy code in this project we are working on.
I'm working on a win form project where I have made a decision to start using entity framework 4.1 for accessing an ms sql db. The code base is quite old and we have an existing data layer that uses data adapters. These data adapters are used all over the place (in web apps and win form apps) My plan is to replace the old db access code with EF over time and get rid for the tight coupling between UI layers and data layer.
So my idea is to more or less combine EF with the legacy data access layer and slowly replace the legacy data layer with a more modern take on things using EF. So for now we need to use both EF and the legacy db access code.
What I have done so far is to add a project containing the edmx file and context. The edmx is generated using database first approach. I have also added another project that contains the POCO classes (by using ADO.NET POCO Entity Generator). I have more or less followed Julia Lerman's approach in her book "Programming Entity Framework" on how to split the model and the generated POCO classes. The database model has been set for years and it's not an option the change the table and the relationships, triggers, stored procedures, etc, so I'm basically stuck with the db model as it is.
I have read about the repository pattern and unit of work and I kind of like the patterns, but I struggle to implement them when I have both EF and the legacy db access code to deal with. Specially when I don't have the time to replace all of the legacy db access code with a pure EF implementation. In an perfect world I would start all over again with a fresh take one the data model, but that is not an option here.
Is the repository and unit of work patterns the way to go here? In order to use the POCO classes in my business layer, I sometimes need to use both EF and the legacy db code to populate my POCO classes. In another words, I can sometimes use EF to retrieve a part of the data I need and the use the old db access layer to retrieve the rest of the data and then map the data to my POCO classes. When I want to update some data I need to pick data from the POCO classes and use the legacy data access code to store the data in the database. So I need to map the data retrieved from the legacy data access layer to my POCO classes when I want to display the data in the UI and vice versa when I want to save data to the data base.
To complicate things we store some data in tables that we don't know the name of before runtime (Please don't ask me why:-) ). So in the old db access layer, we had to create sql statements on the fly where we inserted the table and column names based on information from other tables.
I also find that the relationships between the POCO classes are somewhat too data base centric. In another words, I feel that I need to have a more simplified domain model to work with. Perhaps I should create a domain model that fits the bill and then use the POCO classes as "DAO's" to populate the domain model classes?
How would you implement this using the Repository pattern and Unit of Work pattern? (if that is the way to go)
Alarm bells are ringing for me! We tried to do something similar a while ago (only with nHibernate not EF4). We had several problems running ADO.NET along side an ORM - database concurrency being a big one.
The database model has been set for
years and it's not an option the
change the table and the
relationships, triggers, stored
procedures, etc, so I'm basically
stuck with the db model as it is.
Yep. Same thing! The problem was that our stored procs contained a lot of business logic and weren't simple CRUD procs so keeping the ORM updated with the various updates performed by a stored procedure was not easy at all - Single Responsibility Principle - not a good one to break!
My plan is to replace the old db
access code with EF over time and get
rid for the tight coupling
between UI layers and data layer.
Maybe you could decouple without the need for an ORM - how about putting a service/facade layer infront of your UI layer to coordinate all interactions with the underlying domain and hide it from the UI.
If your database is 'king' and your app is highly data driven I think you will always be fighting an uphill battle implementing the patterns you mention.
Embrace ado.net for this project - use EF4 and DDD patterns on your next green field proj :)
EDMX + POCO class generator results in EFv4 code, not EFv4.1 code but you don't have to bother with these details. EFv4.1 offers just different API which does exactly the same (and it is only wrapper around EFv4 API).
Depending on the way how you use datasets you can reach some very hard problems. Datasets are representation of the change set pattern. They know what changes were done to data and they are able to store just these changes. EF entities know this only if they are attached to the context which loaded them from the database. Once you work with detached entities you must make a big effort to tell EF what has changed - especially when modifying relations (detached entities are common scenario in web applications and web services). For those purposes EF offers another template called Self-tracking entities but they have another problems and limitations (for example missing lazy loading, you cannot apply changes when entity with the same key is attached to the context, etc.).
EF also doesn't support several features used in datasets - for example unique keys and batch updates. It's fun that newer MS APIs usually solve some pains of previous APIs but in the same time provide much less features then previous APIs which introduces new pains.
Another problem can be with performance - EF is slower then direct data access with datasets and have higher memory consumption (and yes there are some memory leaks reported).
You can forget about using EF for accessing tables which you don't know at design time. EF doesn't allow any dynamic behavior. Table names and the type of database server are fixed in mapping. Another problems can be with the way how you use triggers - ORM tools don't like triggers and EF has limited features when working with database computed values (possibility to fill value in the database or in the application is disjunctive).
The way of filling POCOs from EF + Datasets sounds like this will not be possible when using only EF. EF has some allowed mapping patterns but possibilities to map several tables to single POCO class are extremely limited and constrained (if you want to have these tables editable). If you mean just loading one entity from EF and another entity from data adapter and just make reference between them you should be OK - in this scenario repository sounds like reasonable pattern because the purpose of the repository is exactly this: load or persist data. Unit of work can be also usable because you will most probably want to reuse single database connection between EF and data adapters to avoid distributed transaction during saving changes. UoW will be the place responsible for handling this connection.
EF mapping is related to database design - you can introduce some object oriented modifications but still EF is closely dependent on the database. If you want to use some advanced domain model you will probably need separate domain classes filled from EF and datasets. Again it will be responsibility of repository to hide these details.
From how much we have implemented, I have learned following things.
POCO and Self Tracking objects are difficult to deal with, as if you do not have easy understanding of what goes inside, there will be number of unexpected behavior which may have worked well in your previous project.
Changing pattern is not easy, so far we have been managing simple CRUD without unit of work and identity map pattern. Now lot of legacy code that we wrote in past does not consider these new patterns and the logic will not work correctly.
In our previous code, we were simply using transactions and single insert/update/delete statement that was directly sent to database assuming transactions on server side will take care of all operations.
In such conditions, we were directly dealing with IDs all the time, newly generated IDs were immediately available after single insert statement, however this is not case with EF.
In EF, we are not dealing with IDs, we are dealing with navigation properties, which is a huge change from earlier ADO.NET programming methods.
From our experience we found that only replacing EF with earlier data access code will result in chaos. But EF + RIA Services offer you a completely new solution where you will probably get everything you need and your UI will very easily bind to it. So if you are thinking about complete rewriting using UI + RIA Services + EF, then it is worth, because lot of dependency in query management reduces automatically. You will be focusing only on business logic, but this is a big decision and the amount of man hours required in complete rewriting or just replacing EF is almost same.
So we went UI + RIA Services + EF way, and we started replacing one one module. Mostly EF will easily co-exist with your existing infrastructure so there is no harm.

.NET Dual persistence architecture

I'm faced with the challenge of writing an object persistence mechanism that serializes/deserializes to a SQL database and XML files.
For the sake of illustration, imagine I have a graph of objects that has a single root object. Maybe a "tree", for example, which has all manner of child objects -- leaves, brances, nuts, squirrels, birds and the like.
I need a suggestion for an architecture that seamlessly moves between loading & saving a "tree" from a file and/or database. It needs to be able to load a "tree" from a file and save it to a database, or the other way around.
I'm currently using Entity Framework for my SQL persistence, and I'm happy enough with it. For the XML I'm using XDocument, which I also like a lot, but I'm wondering if there isn't some framework out there that already does all this.
Unless you want to do querying on your objects in Sql Server (or there are other sources that may update/manage relational data), using EF to convert into relation schema is a bit overkill. If all you want is to persist your object graph in different mediums then you should consider runtime serialization or DataContractSerializer. Essentially, you will get binary data or XML that you can dump into any storage medium including Sql Server. This will free you from changing relation schema in sql server when your object structures changes. However, you must consider versioning your objects while going from serialization approach.
You can try using the older, yet very nice XmlSerializer.
ps. need to watch out for anything Entity Framework may require from you when loading an object you serialized to a xml file.
Are there any strict requirements around the entities being saved in XML format? If not, another option could be to use SQLite (http://sqlite.phxsoftware.com/) with the entity framework when you need local/filesystem persistence.

Categories