I need to upload a project from Visual Studio to Azure, but I have to share the same DB with other projects. So I guess I need to rename all my models that creates the tables in the DB to prevent any conflict with other projetcs model/tables!?
I started to change the name of one the model and then continued to change in the code and also in IdentityModels.cs file, but will this really work? Do I need to change in other files also? One way to simplify it all, would be to use search and replace, but then I have no control of what is changed!
Any good advice how to replace name of table in DB and all instances?
i think there is a migration plan if you change your model after creating the data base
link :
https://msdn.microsoft.com/en-us/data/jj591621.aspx
Related
I have created an ASP.NET Core web application using the MVC pattern (by following this tutorial) and connected it to a local database that is now populated with some data. I have two questions, if someone please help me understand and answer them:
1) My default connection string is set to the following:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MyAppName;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Is it possible, only by changing the name and path in this connection string, to re-create the exact same database elsewhere with the data that is currently stored in it (for example, as backup)?
I have found the local database here:
C:\Users\my-name\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB
But when I try to copy the .mdf file to back up the database, I get an error that says the file is open and cannot be copied. What is it open in? How can I simply back the db file up?
2) After creating a custom controller, I noticed that all the provided properties of my Personmodel are used in the auto-generated code; e.g. in my case:
public async Task<IActionResult> Create([Bind("Birthday,ID,Username,EmailAddress")] PersonModel personModel)
I thought this would mean that if we change the code in the model class, we need to search for and effect the changes accordingly, but then I realized if I want to keep using auto-generated code, I have to do all the same steps as when I am generating it for the first time, and then when it asks if I want to replace the old code with new code, I choose yes.
Is there a better way of doing this, because this would overwrite my custom code every time and destroy the data stored in my local database. Particularly, when I store data in its local database, and then I decide to change a column name or add something, this would override everything...
How do I go about this situation?
Question 1
The .mdf and other files associated with the database will be in use by the SQL Server service. If you want to take a backup, use SQL Server Management Studio - right-click the database in the object explorer, select Tasks and then Backup. If you want to use the backup database then you need to restore it - again in the object explorer, right-click the "Databases" folder and select Restore Database and then browse to wherever you created the backup file.
Question 2 (updated 7th Sep)
When you change your model classes, you can use the add-migration command in the console to generate a new migration class containing the code to transform the database from its current structure to the new structure which matches the updated models. If the migration can cause data loss, then backup the database and restore the backup under a different name before running update-database, You can then create a script to transform the data from the backup into the new structure of the updated database.
Scaffolded components are a bit different to Entity Framework migrations. Migrations are truly auto-generated classes, and most of the time you wouldn't need to update (or even look at) the generated code. Think of scaffolded components as being more like a kind of template - it's a way of getting started with the classes, methods, markup etc that you're most likely to need, which is quicker than writing it all from scratch. It's not an alternative to writing code though, the intent is that once you've created the scaffolded code, you'll maintain it manually going forward. There is no way (that I know of) to automatically update scaffolded code to match a new model whilst retaining any edits you've made to it. You have two options
Re-scaffold the code and then apply your edits to it
Update the code manually to match the new model
All you can really do is weigh up the two options and decide which one is the least effort.
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.
I have added added Entity Framework to my project and selected Code first from database when creating my models. But the problem is, i couln't find how find how to update existing models and add new models to my project when i make changes on database.
It is very straightforward. Switch on migrations, change/add you classes, create a migration and update your database. See here for example. There are plenty of other sources.
When you change your DB you can run the EF generation again but it will overwrite the existing files so you will lose any changes. If you want to maintain code outside the generated files then you can use partial classes. Or alternatively just code them by hand after the initial auto generation, it's quick once you get used to it! :)
I am using Entity Framework 4 with MVC 3 in Visual Studio 2012 (C#).
I am using database first; there are two separate databases each with its own namespace and with two separate edmx files. Each database has a table with the same name and fields (but different content). When I added the second table I started to get compile errors.
Ambiguity between 'Interface.CodeFormStatus.FormStatusCodeID'
and 'Interface.CodeFormStatus.FormStatusCodeID'
There seem to be some complex workarounds or I could rename one of the tables. Is there not a straightforward solution as this must be a fairly common issue.
I ran into a situation where I had two databases (one an older version of the other) and I needed to integrate both into a single project. Naturally, almost every name conflicted.
I created two separated edmx files for each database, and put each in its own namespace for clarity. I then edited each entity name to reflect which database it was coming from - (e.g. "Activities", which was in both, became "v13Activities" and "v14Activities").
For operations which were to be mirrored between both databases, I wrote a wrapper that included both contexts. This made my code was much less repetitive, and it had less synchronization issues.
Hope this approach helps someone else - it seems like this is an obscure question, and this answer was one of the top results on Google!
Update: In EF 6.1+, there is another solution. You can have "conflicting" names, and separate them with simple namespacing when using the "Code First From Database" option. I would advocate for this solution going forward, as the old XML .edmx style is going to be phased out starting in EF Core.
This worked for me. Just click on the table in the designer (the graphical version not the code) Then in the properties next to the, "Name" attribute you can change the name to something different. This will just change the name within the designer and used more as an alias throughout the application.
If you don't have many tables with the same name, then you could edit entity name in designer (your .edmx file).
So, just double-click a name of one of your CodeFormStatus entities and make it different (for example, change it to CodeFormStatusOther)
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.