Can Database Changes be propagated to Code First Models - c#

I've been practicing the Code First concept on my database. Since I have worked with databases longer than .NET Code Development, I tend to always consider ways to leverage the power of the database and so my standard practice has always been Database first and then use an ORM like EF to generate the context for the DAL.
So please excuse if this may seem like a stupid question. I've been getting accustomed to using the Code Migration utility to create my primary and foreign key relationships, define Primary Keys and etc. Great learning experience but for some tasks I think it is better to simply go straight to the database and run a script. Such as creating check constraints, stored procedures to implement as functions in code and etc.
So my question is, if I perform a task like creating a check constraint in the database is there any way to propagate the change to the code first model? I know the update-migration command will force changes in the model to the database so as I am a beginner to this method I am wondering how can I get Code First to receive changes in the database as opposed to pushing changes out.
I ask because everything I've learned so far seem to enforce the term "Code First" as if when you begin developing in this mode, you cannot reverse the logic if needed.
Is this right or am I simply missing something???
Also, is it considered a common or reasonable practice to use Code First and EF? Seems as though Code First provides the same benefits as EF and so it would seem to be a redundant use of code.

Related

Is using Stored Procedure such a bad idea?

Microsoft has often provided ways to make it easy to develop things that are simple and trivial.
There are certain things that I dislike in EFxx.
First and foremost, the fact that in order to do an update, you need to LOAD the record first, so the operation becomes a 2 step process where maybe you just want to update a boolean value.
Second, I like Stored Procedures because i can run 10 different things within the same connection call where if I were using EFxx I would have to run 10 separate DB calls (or more if update was involved).
My concern and question to the MVC EF gurus is ...
Is using Stored Procedures such a bad idea? I still see EFxx as just another way Microsoft gives us to develop simple programs much faster, but in reality it's not the true recommended way.
Any hint and tip will be much appreciated, specially on the concept of "what's the best way to run an update on EFxx" & "is Stored Procedures bad for EFxx".
You are falling into a logical fallacy. Just because EF is designed to work a certain way doesn't mean you aren't supposed to ever do it a different way. And just because EF may not be good to do a certain thing in a certain way doesn't mean EF sucks or shouldn't be used for anything. This is the All or nothing argument. If it can't do everything perfectly, then it is useless.. and that's just not true.
EF is an Object-Relational Mapping tool. You would only use it when you want to work with your data as objects. You would not use it if you want to work with your data as relational sets (aka SQL).
You're also not stuck with using EF or nothing. You could use EF for queries, and use stored procs for updates. Or the other way around. It's about using the tool that works best for the given situation.
And no, EF is not just for "simple" or "trivial" things. But, using it for more complex scenarios often requires deeper knowledge of how EF works so that you know what its doing under the covers.
Using a stored proc in EF is as simple as saying MyContext.Database.ExecuteSqlCommand() or MyContext.Database.SqlQuery(). This is the most basic way to do so, and it provides rudimentary object to sproc mapping, but it does not support the more complex ORM functionality like caching, change tracking, etc..
EF6 will more fully support sprocs for backing of queries, updates, and deletes as well, supporting more of the feature set.
EF is not a magic bullet. It has tradeoffs, and you need to decide whether it's right for you in the circumstances you're going to use it.
FYI, you're absolutely wrong about needing to get an object before updating it, although that's just the simplest way of dealing with it. EF also implements a unit of work pattern, so if you are doing 10 inserts, it's not going to make 10 round trips, it will send them all as a single prepared statement.
Just like you can write bad SQL, you can write bad EF queries. Just because you are good at SQL and bad at EF doesn't mean EF sucks. It means, you aren't an expert in it yet.
So to your question, no. Nobody has ever said using Sprocs is a bad idea. The thing is, in many cases, sprocs are overkill. They also create an artificial separation of your logic into two different subsystems. Writing your queries in C# means you're writing your business logic entirely in one language, which as a lot of maintenance benefits. Some environments need sproc use, some don't..
This has been asked and answered many times. Like this one.
There will always be pros and cons to both. It's just a matter of what is important to you. Do you just need simple CRUD operations (one at a time)? I would probably use ORMs. Do you do bulk DB operations? Use SPs. Do you need to do rapid development? Use ORMs. Do you need flexibility such that you need full control over SQL? Use SP.
Also, take note that you can reduce the number of DB trips your context in EF does. You can try to read more about different types of EF loading. Also, calling SPs is possible in EF. Data read using SP & Add/Update using SP.

CQS queries - Auto generate ADO Mapping to View models?

I am currently working on an MVC 4 application. I am planning to implement a command query seperation pattern to enhance performance and the structure of the application. I am happy with my commands - which map my view models to my entities use then use nhibernate to save my data.
The commands and queries will be running off the same database.
I am a bit unsure of the best approach to manage my queries. In my last project I used Stored procedures for all of my reads/queries, then used automapper to map my IDataReaders to my ViewModels. This worked ok but the main problem was the turn around time of writing the stored procedures and also when the domain model changed the stored procedures got out of sync.
Therefore, ideally I would like something that auto generated the views or sprocs from my view models. But realistically, I cannot see a way of doing this. As the Sprocs/Views need some knowledge of potentially more that one table. So simply reflecting on the View model properties would not be enough.
I could auto generate a table for each view model, read this during development, then once the domain was stable and before we went to test convert these to views/sprocs?
So I guess what I am asking is:
Has anyone managed to solve the sproc/view auto generation problem I described above? (this would be my favourite outcome!) Or even better has designed a much more graceful solution!
Or is it more sensible to only implement raw ADO reads where they are absolutely necessary - i.e searches, and there dispense with the need for lots of sprocs/views.
But then still separate out my queries into a separate channel (but inside some of them they use NHibernate, whilst others use my ADO reader).
(p.s I have looked at the other stackoverflow CQS related questions and I hope mine is different enough to warrant this question)
What do stored procedures solve for you? Why can't you use NHibernate for reads too? Are the queries NHibernate produces that bad?
If performance of reads is crucial for you, and the shape of your viewmodels is very different from how you store your model - making the denormalization process to a viewmodel too heavy to do on the fly, you might have to consider completely splitting reads and writes.
When you write something, you can raise an event - often done asynchronously - on which subscribers listening can store data on the readside in such a way that it's optimal for reads (close to the shape of your viewmodel). This would make querying really fast.
Since a picture says more than a thousand words..
You can read a good introduction to CQRS here.

Suggestions for starting a entity framework code first project from scratch

I'm trying to create a project from scratch. I'll be using asp .net mvc4 (with asp net web api), and entity framework 5 for data access (all the latest technologies)
Since it's a fresh start, I was thinking on centering my design on my model rather than creating the database first and then creating the EF model, so I though I'd go with a code first approach.
The problem with code first (as far as I see) is that you lose all the scaffolding that EF does for you on a model first scenario (design support, easily generating and maintaining entity relationships 1-1, 1-*, -, etc)
The question is : What tools or templates or snippets or whatever can I use to make my life easier when designing my model?. I want this process to be as painless as possible, since it involves a lot of repetition (FK relationships, for example, are the same always)
Should I use DbContext or something else? Is there some kind of way to start code first but at the same time maintain an edmx model, or those are mutually exclusive?
thanks!
The great thing about EF Code First is that you don't need any scaffolding. You don't need an EDMX model, you don't even need to specify the exact nature of relationships, it's all based on conventions. For example your classes must have a property called Id, which will be taken to be the Primary Key of the table. All string based fields are generated as nvarchar(MAX). Of course some conventions might not be what you want and Code First supports this through pluggable conventions (you can remove most conventions and create your own)
You should do some of the basic tutorials to get an idea of how the Code First flow works as it's an entirely different proposition to the Db First approach.

Best Practice - Mixing Table-Entities with View-Entities in EntityFramework?

I have a legacy database that I'd like to interact with Entity Framework.
The database is highly normalised for storing information about flights. In order to make it easier to work with some of the data, a number of SQL Views have been written to flatten data and to pivot certain multi-table joins into more logical information.
After quickly looking over this I see two problems with using Views in EF.
The Views contains lots and lots of Keys. Some quick googling seems to indicate I will need to manually edit the EDMX file to remove this info.
The Views don't have any relationships to the other table entities. These associations need to be manually added in order to link a View -> Table.
Both of these seem like major pain points when it comes to refreshing the Model from the DB, when teh DBA team make changes.
Is this just something you need to "put up with" when working with EF or are there any suggested patterns/practices to deal with these.
Mixing Table-Entities with View-Entities is ok and largely depends on your requirements.
My experience has been these are things you are going to have to deal with.
When I first started using Entity, I used views a lot because I was told I needed to use them. As I became more familiar with Entity I began to prefer the use of table-entities over view-entities; mainly because I felt I had more control. Views are ok when you are presenting read-only info, or as you described (flattend data, pivots, joins etc.); however, when your requirements change and you now have to add CRUD, you are going to have to use stored procedures or change your model to use table-entites anyway, so you might as well use table-entities from the start.
The Views contains lots and lots of Keys. Some quick googling seems to
indicate I will need to manually edit the EDMX file to remove this
info.
This wasn't ever really a problem for me. You can undo keys of the view-entity in the designer. If your talking about doing this for the view in the storage layer, then yes, you can, to make it work, but as soon as you update your model from the database, you are going to have to do this over again -- I wouldn't recommend doing this. You are better off working with your DBA to adjust the key constraints in the database.
The Views don't have any relationships to the other table entities.
These associations need to be manually added in order to link a View
-> Table.
This was often a problem for me. Sometimes you are able to add keys and create relationships without any problems, but often times you may have to change the keys and/or relationships in the db to make it work -- this depends on your requirements; you may have to deal with this even when using table-entities.
Hope this helps.
I've been in a similar situation as we transitioned into using Entity Framework.
The first step was to start with a blank EF model and add the tables when we created the domain service calls. This at least meant that the model wasn't crazy to start with! Then the plan was to try and not use views as much as possible and move that kind of logic into the domain service, where at least it could be tested, and slowly deprecate the CRUD stored procedures. It's worked fine and there haven't really been any major problems.
In practice there are still some views, mainly used for situations that need to be performant, Fortunately these views can be considered in isolation (for read only grids) and have been left as such in the model with no associations. Adding the keys in would I'm sure be annoying.
Editing the EDMX file is okay, but sometimes on a model refresh these changes can get lost. This has happened to me particularly when EF thinks a table is a view. And yes it's a pain and something that has just been put up with.

Entity Framework Code First: good way to convert legacy business objects to EF?

I have been given responsibility of a VB6 app with a .NET component.
The previous programmer, for reasons unclear, thought it would be a good idea to write out business objects in .NET that represent virtually all of the important data in the app. They match quite well to the existing database tables and structure.
Would using EF's Code First on these objects be a good way to create a new EF model if I am rewriting the app in C#?
Code first works quite well with existing data models. The fluent mappings are pretty intuitive.
I've been transitioning a big application to EF4.1 over the last couple of months and haven't run into any real difficulties.
In short, I like it a lot.
Im sure you can use the code first approach with the existing business objects or you can use a database first approach and generate your model based on the database, for example.
If you business objects closely match your database then might be faster to use the database first approach.

Categories

Resources