Having all my prior Entity Framework experience with 4.1 and a Database First approach, I've just dived into Entity Framework 6.1.2 and Code First from Database.
I have generated my context and entities without a problem but I want to customize the way that EF generates the entities; I want the entities to go from their database name of TABLE_NAME to an entity name of TableName.
I've followed the instructions here and installed the CSharp Code Templates.
I've also found a couple of examples for applying Pascal Case naming (e.g. here) but can't figure out a way to apply the techniques to the NuGet CodeTemplates to cover all scenarios (e.g. I can apply pascal case to simple properties and even NavigationProperties but I can't do it when MethodChain is used in Context.cs.t4 for relationships in OnModelCreating)
There's a similar sort of question here but it applies to EF6 Power Tools which doesn't quite match the scenario now that the Code First from Database functionality is consolidated in EF6.
Am I missing something blindingly obvious? I just want to save myself updating hundreds of entity names after using Code First from Database.
Refactor all your entities to PascalCase then map them like this:
modelBuilder.Entity<TableName>().ToTable("TABLE_NAME");
Related
I have a situation where a multitude of very similar but not identical legacy databases is being reverse engineered into a C# model using dotnet ef dbcontext scaffold. Due to the variety of the databases there is no single definitive source. The closest one have a column in a couple of tables that should not be in the C# model.
I had a look at https://github.com/dotnet/efcore but could not immediately see options or paths in the code allowing this finegrainedness.
Is there a way to add metadata to the database to skip columns is skipped?
There is currently no way to do this as there is no option for that in scaffolding options
Take a look at DatabaseModelFactoryOptions.cs and EntityFrameworkCore.psm1 for more info
I'm having a hard time just defining my situation so please be patient. Either I have a situation that no one blogs about, or I've created a problem in my mind by lack of understanding the concepts.
I have a database which is something of a mess and the DB owner wants to keep it that way. By mess I mean it is not normalized and no relationships defined although they do exist...
I want to use EF, and I want to optimize my code by reducing database calls.
As a simplified example I have two tables with no relationships set like so:
Table: Human
HumanId, HumanName, FavoriteFoodId, LeastFavoriteFoodId, LastFoodEatenId
Table: Food
FoodId, FoodName, FoodProperty1, FoodProperty2
I want to write a single EF database call that will return a human and a full object for each related food item.
First, is it possible to do this?
Second, how?
Boring background information: A super sql developer has written a query that returns 21 tables in 20 milliseconds which contain a total of 1401 columns. This is being turned into an xml document for our front end developer to bind to. I want to change our technique to use objects and thus reduce the amount of hand coding and mapping from fields to xml (not to mention the handling of nulls vs empty strings etc) and create a type safe compile time environment. Unfortunately we are not allowed to change the database or add relationships...
If I understand you correct, it's better for you to use Entity Framework Code First Approach:
You can define your objects (entities) Human and Food
Make relations between them in code even if they don't have foreign keys in DB
Query them usinq linq-to-sql
And yes, you can select all related information in one call.
You can define the relationships in the code with Entity Framework using Fluent API. In your case you might be able to define your entities manually, or use a tool to reverse engineer your EF model from an existing database. There is some support for this built in to Visual Studio, and there are VS extensions like EF Power Tools that offer this capability.
As for making a single call to the database with EF, you would probably need to create a stored procedure or a view that returns all of the information you need. Using the standard setup with lazy-loading enabled, EF will make calls to the database and populate the data as needed.
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.
I'm starting a new application that must use an existing database that use some naming conventions that are really annoying in .net (table names start with several trigrams that specify the business domain of the table, column names start with the tables trigram, trigrams are in uppercase and separated by underscores, etc.,).
What I'd like to do is to write a simple renaming rule (this is as simple as finding the last underscore and take everything after that) and apply it in Entity Framework. I don't really want to edit the names one by one in the editor, especially because the database might change and I don't want to do it several times.
I'm using Database First (as the database already exists and it is "the master"), and EF 4.x DbContext Generator and it works really great out of the box (with badly named classes and properties though).
I edited the T4 templates in order to rename the generated entities and properties, but when I try to perform any request, the DbContext object can't find the table that matches with the entity I'm trying to request and I get this exception :
The entity type [Entity Name] is not part of the model for the
current context.
This is obvious why it doesn't find the table : nothing tells it how to match the entity name and the table as I changed it on the fly.
I read that I can add instructions in the OnModelCreating(DbModelBuilder modelBuilder) method but this is not used in Database First (and the default T4 template adds an exception in it, just in case).
So now I'm stuck, I don't know how to specify that matching.
Here are several ideas I have but not sure if it's correct or doable :
Using the "plural / singular" API to change the name of the Entity ? Sounds like a dirty workaround. But it might work (didn't try though).
Finding a way to edit the EDMX file on the fly.
Editing the EDMX afterwards but it might complicate the process (edit in the designer, then execute a tool to alter the EDMX, then run custom tool to regenerate entities and DbContext... while today I just have to edit in the designer).
Using Code First (as it seems easier to use different entity names than table names, through attributes or instructions in the DbContext class), but it sounds like it would not be more complicated to use it with an existing database.
Any idea ? Or did I miss something ?
You won't be able to use a T4 transform for this, as you want to change the content of the actual .edmx file to map your store entity names (with the obnoxious prefixes) to your sanitized conceptual entity names.
Instead, you're better off writing an application that takes an .edmx file as input and sanitizes the names under the conceptual model tag and modifies the mapping names to reflect the sanitized names. I understand that this is your third option and that you wanted to avoid this if possible, but this is the most straightforward way to go about it. Bear in mind that you'll only have to run this tool when you add new tables or columns.
I got confused on what are the differences between Linq-to-SQL and Entity Framework when following the database first approach as I can not find any clear differences.
In my case when I was using Linq-to-SQL I used to create the tables then I use Linq-to-SQL to create the classes that represents the tables, and now when I switch to Entity Framework I am still following the same steps (creating the database tables then create the associated classes using EF).
And I am interacting with these classes on the same way, for example I used to query the User class using the same syntax and approach but one time when the User class was created using Linq-to-SQL and the other time when it was created using EF, so where is the difference ?
public IQueryable<User> findstudents(string term)
{
return from student in entities1.Users
where student.UserID.Contains(term)
select student;
}
Second question if I use EF to map the tables into classes, is it still possible to use Linq-to-SQL in the same application to query the EF classes?
LINQ is a base technology - that's the syntax that gives you the SQLish query options in C# - that's totally independent of whether you use Linq-to-SQL or EF. So if you want to query your data classes using the LINQ syntax - you can do that with both frameworks - but once you use Linq-to-SQL and once you use Linq-to-Entities. You cannot use Linq-to-SQL against an Entity Framework EDMX model.
Linq-to-SQL is great
if you need very simple 1:1 mapping - one table equals one class in your domain model
if you never need anything else but SQL Server (Linq-to-SQL doesn't support anything else)
if you want to be up and running really quickly
Entity Framework on the other hand
supports multiple backends (SQL Server, Oracle, Firebird - other will likely follow)
supports a full conceptual data modelling strategy - you define the physical model in the database, the conceptual model in your app, and the mapping between the two
gives you the ability to handle things like mapping a single business entity to several tables
support table-per-hierarchy and table-per-class inheritance scenarios
support refreshing/updating your model (EDMX file) from the database when things change (in Linq-to-SQL, you basically have to drop + recreate those entities involved - thus loosing all your customizations you might have made)
In brief: Linq-to-SQL is a great, simple and lean'n'mean ORM for SQL Server - use it, if it does all you need. Entity Framework is quite a different beast, much more capable, but also more complex, much bigger - perfect for your next enterprise-critical app, but probably overkill for your personal blog app :-)
If you want to create something that's "future-proof" and will use the OR technology that Microsoft is pushing into the future, then you should go with Entity Framework. Especially in v4, it's also a lot easier to use, a lot more slimmed down and more useful than ever before.