As I need to work with C# and MySQL, I recently installed linq2db via its NuGet package. Once installed, I found out it came with a very sweet feature which is unmentioned in the docs: a set of T4 templates to auto-generate DB class and tables' POCOs! (WOW!)
So I decided to run T4s instead of write down my POCOs by myself, but here comes the wrong part: tables list for the db is not found, thus only the db class is created.
The following demo project generates tables for MySql
https://github.com/linq2db/examples/tree/master/MySql/GetStarted/DataModels
Regarding the auto generated classes.
Are you sure that you completed step 2?
It refers to modifying the line after the end of the comments (after the description of step 5) from
LoadMySqlMetadata("MyServer", "MyDatabase", "root", "TestPassword");
to something sensible.
After that, you'll get a 'sub'-file of the CopyMeMysql.tt (in VS, click expand icon to the left of the file in the project) called CopyMeMysql.generated.cs.
Related
I want to create an Entity Framework Model based on database using VS 2015.
There is some problem:
1) When I want to create model I get this warning:
2) When I create mode some file being generate like T4.
3) Generated class hasn't Data Annotations like :
[EdmEntityTypeAttribute(NamespaceName="SomeModel", Name="tblCode1")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
4) In our group there are some people that have VS 2013 or 2010 that they can't use this type of models.
How I can create model using VS 2015 like VS 2010 or 2013 without T4 (Just 2 files like below)
Short answer:
You need to change the Code Generation Strategy property of the edmx from "T4" to "Legacy ObjectContext" and delete the .tt nodes from the Solution Exporer.
Long answer:
Here are the steps needed:
(1) Assuming you start by selecting "Add -> New Item -> ADO.NET Entity Data Model -> EF Designer from database".
(2) Follow the "Entity Data Model Wizard". The next is very important. When you get to the screen which asks you for the EF version you want to use, make sure you select EF 5.0, otherwise T4 template will be the only option you have:
(3) Finish the wizard. Say OK to security warnings like your first screenshot. The project structure will look like your second screenshot.
(4) Open the edmx file in a designer. Look at the Properties Window, there is a property called Code Generation Strategy which by default is "T4"
Change the property to "Legacy ObjectContext"
(5) Delete YourModel.Context.tt and YourMdel.tt nodes from the Solution Explorer and you are done.
A bit boring, but does what you want. The drawback is that you are limited to an outdated EF version, and the upcoming EF7 will retire edmx at all, so it might be a good time to start thinking of switching to the Code First approach. But until then, hope the above will help to keep your current process.
For generate "Code first" model (obtain a code first model starting from database) you can also use Code Smith Generator. You can start from POCO classes templates (or from NHibernate templates if you need serialization, IDataErroInfo, INotifyPropertyChanged, and so on implemented) and customize them is really simple (the syntax is based on ASP). Probably there is also a free version.
Looking around I found also an article and an open source tool that extract POCO classes from SQL Server database.
http://www.codeproject.com/Articles/892233/POCO-Generator
I am new to Entity Framework 6 Code First and am trying to perform what I thought would be a simple task. I want to create a SQL View and then have an Entity in my database context that I can use to query the view.
I have tried articles such as this but the key difference in my case is that the SQL View is not an existing view coming from another existing database.
I examined the proposition made in this article but it seems like overkill to me that I would need to create some extension methods to do something as simple as create a view/entity combo and use it in my database context.
Am I missing something? I know it would be much easier if I weren't using Code First but please keep in mind it's Code First and I am trying to create a view, not reuse one from an existing database.
Colin and Kevin, Thank you for the link to your answer on the other post and your concise answer. I have used several resources to finally create a queryable entity based on a new SQL view. Just in case anyone else is new to EF 6.0 Code First and is just getting their feet wet, I do have a few steps that will hopefully benefit others in the future.
It may seem obvious to more seasoned Entity Framework developers, but in order to execute the 'Migration' approach you need to disable automatic migrations and actually dive into the guts of the Code First Migrations inner workings. Since automatic migrations is turned on out of the box, I had already created a fairly complex database with seed scripts all relying on automatic migrations and rebuilding the database on every run of my application. This post helped me wipe my migrations history and get to square 1 with automatic migrations turned off (I went with the web.config approach in case you were wondering)
After I had cleared my migrations information, I deleted the mdf from within solution explorer. That guaranteed that I wouldn't run into any problems when running Update-Database (further down the list of steps).
In the Package Manger console, I then executed Add-Migration Initial to generate an "Initial" migration. The result of this was the editable Up and Down methods as described in Colin's answer. I then followed the steps in Colin's answer by commenting out the table create statement (Entity Framework tries to create a table but we really want to create a view and map it to the Entity) and inserting my own view create sql statement at the end of the Up method. It's important to put the create statement after the creation of any tables that it may depend on. I also performed my Seed activities in the Configuration.Seed method instead of in my Context's Seed method. I see how this would be important if you were dealing with multiple migrations. Finally, as Colin suggested I added the table mapping to my context's OnModelCreating event.
The final step in this was to actually apply the migration to the database. In order to do that, in the Package Manager console you execute the Update-Database command. That statement will rebuild the database with the "Initial" migration you created and edited in earlier steps.
It still surprises me that I need to do all of this custom work to create a view and map it to an entity with Code First, but at the end of the day it was helpful in getting me started on migrations as you can only rely on the "automatic migrations" for so long anyways.
You can manually add the sql to create the view to a migration then consume it as per your first link.
The answer in the link provided by Colin does the job.
In case there are lots of views to be created, it can be a good idea to save the view queries in separate files and add them in a resource (.resx) file instead of hard-coding the sql queries in the Migration Up() method.
For e.g.
public override void Up()
{
Sql("ResourceFileName.ResourceName");
}
instead of hard coding like
{
Sql("EXEC ('CREATE View [dbo].[ClientStatistics] AS --etc");
}
In a class library Ado.net Entity Data Model is has generated POCO classes. These were generated fine for the first time. But database changes are not being reflected. In edmx diagram right clicking and choosing Update Model from Database show newly created table but it do not add table even after selecting it to add.
I tried running .tt (by right click and Run custom tool) but even it did not regenerated the Poco classes as per latest DB changes.
Help please
Not a fix but a workaround: Is it not an option to simply remove and regenerate the EDMX and the generated classes? That's what I do, it is much easier than working with the update feature, and the result seems to be the same. Your POCO extensions still remain the same and functional.
I use database first and I have my SQL upgrade scripts, the generated EDMX and my Generated models in source control and the changes there are very easy to manage. Here is a rough outline of my DB upgrade process for each version:
Create .sql script for the upgrade, statements like CREATE TABLE etc.
Delete generated files: Model.Context.tt, Model.tt, Model.edmx
Remove Entities string from Web.config (if you use it)
Create the EDMX and Context files the same way you did for the first time
If you use source control (I hope you do!) check what has changed
Test
Commit!
In my case i needed to save ModelName.edmx, then classes were generated.
Ensure that connections string in app.config is correct. I was using a DataDictionary and my connection string had the following path:
data source=|DataDirectory|*.sqlite
Thus, it wasn't updating. Because this DataDirectory variable was being resolved at runtime.
We are using Entity Framework 6 with Model-First, which by default results that our entities, the dbcontext, the .tt files, and the model files are crammed in a single folder, without any structure.
I would like to achieve some separation, at least something like this:
Project root/Entities/entities generated from model
Project root/Repository/everything else (.tt, .edmx, etc...)
Is this possible?
It is not. EF is in charge of where it puts stuff and where it expects them to be; you can't change that.
What you could do in order to get a bit closer to what you want is to use EntityFramework Power Tools to reverse engineer the database and produce a set of POCO classes that can be used as your data access.
It's often described as Code-Second I believe.
You can installed the Power Tools and then select the location in your solution where you want the classes to be and then right-click and select "Reverse Engineer Database" {sic}
sure you can! I don't know what do you mean by
Project root/Entities/entities generated from model
Project root/Repository/everything else (.tt, .edmx, etc...)
but you can even separate the assembly. you can have you domain entities, repository and Context class in an assembly or in a namespace.(it's better to do that for make you app maintainable). take a look at this and this blog posts. hope it helps
I started a new project C#, and I used the "enable-migrations" command in the package console window. This naturally added migrations to my project. I then set automatic migrations to true, so that as I call "update-database" it will create my tables for me with all keys and that.
The only problem is that I have multiple websites where want to do this, which all use the ASP.NET membership provider to login. Which through automatic code migrations create a bunch of account tables for me to use. But the tables are all called the same, so if I do this targeting the same database for different sites they will overwrite eachother. So the question I got is this: How can I specify a prefix for my tables created by the entity framework?
I've seen several ideas on how to do this while searching, but they didn't work for me (the necessary properties wasn't there for some reason and so on.)
Thank you
Xenoxsis
I'm not sure how do you plan to do just that - if I'm getting it right you'd want to keep one database (shared) in between number of web sites - yet, have each site has its own membership tables, named differently, with different prefixes, right?
First problem is that for each Db/table name change - you need a 'code to match' - i.e. code first entities and code, the 'migration table' in the Db - and tables are all in sync - so it could all work together as it should. In that sense, just changing script or table names in Db won't work. It has to be done at the level of attributes (as #Steven suggested) or fluent configuration.
Which in your case, it means that somehow you'd need to 'build' separate configurations for each site, deploy them separately (code) to each site - and build one mega Db that contains all the small variants of each merged together.
That's going to be tough to manage - but you could try (what I described above) - I have no idea if it'd work (as this requires lot of 'infrastructure' to try this one) - but maybe along these lines...
put Table attributes (or via fluent config)
Build code - 'vary' the Table names for each - and rebuild (ideally you might need to employ some tool, code-generator to do this automatically in a batch - i.e. you build, copy files externally, change names and repeat)
Build 'migrations' for each case (Table name) also - save migrations
as files - and also do Update-Database -Script to save the actual
scripts for each case (important).
Save each migration - or we can
say a 'script' to represent.
Once done - you'd need to merge the
migrations - scripts - into one big master script - i.e. remove the
identical set of tables (leave just one of course) - and copy all
different sets for membership tables.
Remove the migration table
from the database - as that'd surely be out of sync and won't let you
do anything (or there is also a flag in code I think to just ignore
that, don't have it right now). For details see below in my other
post.
Deploy one master Db - using script you created
Deploy the
specific code - to each of the sites.
Pray it'd all work :)
There must be something smarter - but on the other hand, migrations are not made to work for such scenarios, so it's going to be hard if not impossible to pull this off.
Some general info that might help...
How to synchronize migrations with existing databases - geared toward production scenarios, maintaining Db-s and CF to match. It's not exactly what you need but has a detailed description, possible ways to resolve this which I wrote a while ago...
MVC3 and Code First Migrations - "model backing the 'blah' context has changed since the database was created"
To summarize...
What works for me is to use Update-Database -Script
That creates a script with a 'migration difference', which you can
manually apply as an SQL script on the target server database (and you
should get the right migration table rows inserted etc.).
If that still doesn't work - you can still do two things...(more inside)...
I don't know of anyway to make Entity Framework do this automatically across all entities. But you could force a table name, or schema using attributes or fluent API to get the desired effect. For example:
[Table("[put prefix here]_Users", Schema = "[put schema here]")]
public class User {
// ...
}