Just a quick post on fixing up a migration error after I added new config to startup.cs via DI. The error after running add-migration was pretty unintuitive:
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
To find out a bit more I ran the following:
This revealed the fact that there was an issue with adding my config line. The error stated that I had to have an empty constructor which led me on a bit of a wild goose chase.
The solution was simply a missed entry in application.json. In my case it was an omitted “assembly” section. Having said that, I did come across a few instances where people had the same problem when omitting commas etc.
Hopefully that’s able to get you on the right track!
I ran into the following error after adding model validation attributes to a database with existing values:
String or binary data would be truncated.
The statement has been terminated.
The solution is pretty straightforward if you’re happy to truncate the values. Simply run the query below, swapping Title for your column name, Products for your table name and 25 for your new column length:
SET Title = LEFT(Title, 25)
WHERE LEN(Title) > 25
You should then be able to run update-database without any issues:
Specify the ‘-Verbose’ flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201806240741543_product_validation].
Applying explicit migration: 201806240741543_product_validation.
Running Seed method.
Just a quick post on how to view the generated sql in entity framework. To start with, just add the following line to your db context constructor:
public class TestDbContext : DbContext
public TestDbContext() : base("name=TestDbContext")
this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); //This line
With this line added, you should now be able to see all of your generated sql in the output window.
SELECT TOP (1)
[Project1].[VidId] AS [VidId],
[Project1].[CreatedAt] AS [CreatedAt],
[Project1].[Check] AS [Check],
[Project1].[SourceCheck] AS [SourceCheck]
FROM ( SELECT
[Extent1].[VidId] AS [VidId],
[Extent1].[CreatedAt] AS [CreatedAt],
[Extent1].[Check] AS [Check],
[Extent1].[SourceCheck] AS [SourceCheck]
FROM [dbo].[Vids] AS [Extent1]
WHERE [Extent1].[VidId] < @p__linq__0
) AS [Project1]
ORDER BY [Project1].[VidId] DESC
-- p__linq__0: '535' (Type = Int32)
-- Executing at 28/06/2014 5:00:16 PM +10:00
-- Completed in 0 ms with result: SqlDataReader