notes ef core - deventry/uosweb-docs-en GitHub Wiki
http://www.stum.de/2016/08/24/thoughts-on-orms-2016-edition/
https://blogs.msdn.microsoft.com/dotnet/2016/07/29/entity-framework-core-1-1-plans/
https://blogs.msdn.microsoft.com/dotnet/2016/06/27/entity-framework-core-1-0-0-available/
http://6figuredev.com/technology/generic-repository-dependency-injection-with-net-core/
http://www.codeproject.com/Articles/114262/6-ways-of-doing-locking-in-NET-Pessimistic-and-opt
https://msdn.microsoft.com/en-us/library/bb738618(v=vs.100).aspx http://blogs.u2u.be/diederik/post/2010/05/31/Optimistic-concurrency-using-a-SQL-DateTime-in-Entity-Framework-40.aspx
Timestamp/row version A timestamp is a property where a new value is generated by the database every time a row is inserted or updated. The property is also treated as a concurrency token. This ensures you will get an exception if anyone else has modified a row that you are trying to update since you queried for the data. How this is achieved is up to the database provider being used. For SQL Server, timestamp is usually used on a byte[] property, which will be setup as a ROWVERSION column in the database.
The above seems problematic if I want to be able to support multiple database platforms. Can I use the same model for all dbs? http://stackoverflow.com/questions/33970569/best-way-to-handle-optimistic-concurrency-with-entity-framework-7
By using optimistic locking you only detect the concurrency problem.
A concurrency conflict occurs when one user displays an entity's data in order to edit it, and then another user updates the same entity's data before the first user's change is written to the database. If you don't enable the detection of such conflicts, whoever updates the database last overwrites the other user's changes. In many applications, this risk is acceptable: if there are few users, or few updates, or if isn't really critical if some changes are overwritten, the cost of programming for concurrency might outweigh the benefit. In that case, you don't have to configure the application to handle concurrency conflicts.
John clicks Save first and sees his change when the browser returns to the Index page, then Jane clicks Save. What happens next is determined by how you handle concurrency conflicts. Some of the options include the following:
You can keep track of which property a user has modified and update only the corresponding columns in the database. In the example scenario, no data would be lost, because different properties were updated by the two users. The next time someone browses the English department, they'll see both John's and Jane's changes � a start date of 8/8/2013 and a budget of Zero dollars.
This method of updating can reduce the number of conflicts that could result in data loss, but it can't avoid data loss if competing changes are made to the same property of an entity. Whether the Entity Framework works this way depends on how you implement your update code. It's often not practical in a web application, because it can require that you maintain large amounts of state in order to keep track of all original property values for an entity as well as new values. Maintaining large amounts of state can affect application performance because it either requires server resources or must be included in the web page itself (for example, in hidden fields) or in a cookie.
You can let Jane's change overwrite John's change. The next time someone browses the English department, they'll see 8/8/2013 and the restored $350,000.00 value. This is called a Client Wins or Last in Wins scenario. (All values from the client take precedence over what's in the data store.) As noted in the introduction to this section, if you don't do any coding for concurrency handling, this will happen automatically.
You can prevent Jane's change from being updated in the database. Typically, you would display an error message, show her the current state of the data, and allow her to reapply her changes if she still wants to make them. This is called a Store Wins scenario. (The data-store values take precedence over the values submitted by the client.) You'll implement the Store Wins scenario in this tutorial. This method ensures that no changes are overwritten without a user being alerted to what's happening.
http://www.agiledata.org/essays/concurrencyControl.html
http://seldo.com/weblog/2011/08/11/orm_is_an_antipattern
Edge of the Web: Entity Framework Core: The Future of EF for ASP.NET Core https://channel9.msdn.com/Blogs/DevRadio/DR1644
Azure Table storage is very low cost which makes it attractive but not sure all the needed query techniques are available pagination would be challenging or impossible even simple things like count are difficult http://stackoverflow.com/questions/28667601/get-the-azure-table-row-count http://stackoverflow.com/questions/28599511/add-pagination-mvc-and-azure-table-storage
http://jeremybytes.blogspot.com/2014/02/demystifying-var-keyword-in-c.html
C# Reference: https://msdn.microsoft.com/en-us/library/ms173224.aspx
http://stackoverflow.com/questions/3485317/entity-framework-4-single-vs-first-vs-firstordefault
Find() - when you want to get an item by primary key. This will return null if it can't find an item. It will look in the context before going to the database (as pointed out by Yaron in the comments) which can be an important efficiency factor if you need to get the same entity multiple times while the same context is alive.
Single() - when you expect exactly one item to be returned by a query. This will throw an exception if the query does not return exactly one item.
SingleOrDefault() - when you expect zero or one items to be returned by a query (i.e. you are not sure if an item with a given key exists). This will throw an exception if the query does not return zero or one items.
First() - when you expect one or more items to be returned by a query but you only want to access the first item in your code (ordering could be important in the query here). This will throw an exception if the query does not return at least one item.
FirstOrDefault() - when you expect zero or more items to be returned by a query but you only want to access the first item in your code (i.e. you are not sure if an item with a given key exists)
http://www.mikesdotnetting.com/article/257/entity-framework-recipe-grouping-by-year-and-month
http://stackoverflow.com/questions/818642/singleordefault-how-to-change-the-default-values
http://stackoverflow.com/questions/6033390/what-is-the-most-reasonable-way-to-find-out-if-entity-is-attached-to-dbcontext-o/6037277#6037277 http://stackoverflow.com/questions/10027493/entityframework-code-first-check-if-entity-is-attached
http://ef.readthedocs.org/en/latest/modeling/configuring.html
https://github.com/aspnet/EntityFramework/wiki/Configuring-a-DbContext
https://github.com/aspnet/EntityFramework/wiki/Guiding-Principles
https://github.com/aspnet/EntityFramework/wiki/Security
https://github.com/aspnet/EntityFramework/wiki/Visual-Studio-Publish-Integration
https://github.com/aspnet/EntityFramework/wiki/Writing-an-EF7-Provider
http://blogs.msdn.com/b/adonet/archive/2014/10/27/ef7-v1-or-v7.aspx
http://wildermuth.com/2015/3/17/A_Look_at_ASP_NET_5_Part_3_-_EF7
https://channel9.msdn.com/Blogs/Seth-Juarez/Migrations-in-Entity-Framework-7-with-Brice-Lambson
http://www.jerriepelser.com/blog/moving-entity-framework-7-models-to-external-project
dnx ef migrations add Initial
http://www.jerriepelser.com/blog/resolve-dbcontext-as-interface-in-aspnet5-ioc-container
http://davidzych.com/unit-testing-entity-framework-7-with-the-in-memory-data-store/
dnx ef --help Entity Framework Commands 7.0.0-rc1-16348
Usage: dnx ef [options] [command]
Options: --version Show version information -?|-h|--help Show help information
Commands: database Commands to manage your database dbcontext Commands to manage your DbContext types migrations Commands to manage your migrations
Use "dnx ef [command] --help" for more information about a command.
dnx ef --help migrations Entity Framework Commands 7.0.0-rc1-16348
Usage: dnx ef [options] [command]
Options: --version Show version information -?|-h|--help Show help information
Commands: database Commands to manage your database dbcontext Commands to manage your DbContext types migrations Commands to manage your migrations
Use "dnx ef [command] --help" for more information about a command.
dnx ef migrations --help
dnx ef database --help
Usage: dnx ef migrations [options] [command]
Options: -?|-h|--help Show help information
Commands: add Add a new migration list List the migrations remove Remove the last migration script Generate a SQL script from migrations
Use "migrations [command] --help" for more information about a command.
dnx ef migrations add --help
Usage: dnx ef migrations add [arguments] [options]
Arguments: [name] The name of the migration
Options: -o|--outputDir The directory (and sub-namespace) to use. If omitted, "Migrations" is used. -c|--context The DbContext to use. If omitted, the default DbContext is used -p|--targetProject The project to add the migration to. If omitted, the current project is used. -e|--environment The environment to use. If omitted, "Development" is used. -v|--verbose Show verbose output -?|-h|--help Show help information
dotnet ef migrations add Initial -c CoreDbContext dotnet ef migrations add Initial -c LoggingDbContext
dotnet ef migrations add RemoveCurrecncy -c CoreDbContext dotnet ef migrations add Limitfieldsize -c CoreDbContext dotnet ef migrations add cleanup20160617 -c CoreDbContext dotnet ef migrations add cleanup20160617-2 -c CoreDbContext
dotnet ef migrations add changes20160701 -c LoggingDbContext
No parameterless constructor was found on 'LoggingDbContext'. Either add a parameterless constructor to 'LoggingDbContext' or add an impleme ntation of 'IDbContextFactory' in the same assembly as 'LoggingDbContext'.
C:_joe__projects__cloudscribe\rc2\cloudscribe.Logging\src\cloudscribe.Logging.EF>
C:_joe__projects__cloudscribe\rc2\cloudscribe.Logging\src\cloudscribe.Logging.EF>dotnet ef migrations add Initial -c LoggingDbContext Project cloudscribe.Logging.Web (.NETStandard,Version=v1.5) was previously compiled. Skipping compilation. Project cloudscribe.Logging.EF (.NETStandard,Version=v1.5) was previously compiled. Skipping compilation. This preview of Entity Framework tools does not support targeting class library projects in ASP.NET Core and .NET Core applications. See htt p://go.microsoft.com/fwlink/?LinkId=798221 for details and workarounds.
C:_joe__projects__cloudscribe\rc2\cloudscribe.Logging\src\cloudscribe.Logging.EF>
dnx ef database --help
Usage: dnx ef database [options] [command]
Options: -?|-h|--help Show help information
Commands: update Updates the database to a specified migration
Use "database [command] --help" for more information about a command.
dnx ef database update --help
Usage: dnx ef database update [arguments] [options]
Arguments: [migration] The target migration. If '0', all migrations will be reverted. If omitted, all pending migrations will be applied
Options: -c|--context The DbContext to use. If omitted, the default DbContext is used -p|--targetProject The project with the Migration classes. If omitted, the current project is used. -e|--environment The environment to use. If omitted, "Development" is used. -v|--verbose Show verbose output -?|-h|--help Show help information
C:_joe__projects__cloudscribe\rc2\cloudscribe.Logging\src\cloudscribe.Logging.EF>dotnet build Project cloudscribe.Logging.Web (.NETStandard,Version=v1.5) was previously compiled. Skipping compilation. Project cloudscribe.Logging.EF (.NETCoreApp,Version=v1.0) will be compiled because inputs were modified Compiling cloudscribe.Logging.EF for .NETCoreApp,Version=v1.0
Compilation succeeded. 0 Warning(s) 0 Error(s)
Time elapsed 00:00:01.8645724
C:_joe__projects__cloudscribe\rc2\cloudscribe.Logging\src\cloudscribe.Logging.EF>dotnet ef migrations add Initial -c LoggingDbContext
Project cloudscribe.Logging.Web (.NETStandard,Version=v1.5) was previously compiled. Skipping compilation.
Project cloudscribe.Logging.EF (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at cloudscribe.Logging.EF.Startup..ctor(IHostingEnvironment env) in C:_joe__projects__cloudscribe\rc2\cloudscribe.Logging\src\cloudscr
ibe.Logging.EF\Startup.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.EntityFrameworkCore.Design.Internal.StartupInvoker.Invoke(Type type, String[] methodNames, IServiceCollection services)
at Microsoft.EntityFrameworkCore.Design.Internal.StartupInvoker.ConfigureServices()
at Microsoft.EntityFrameworkCore.Design.DbContextOperations..ctor(ILoggerProvider loggerProvider, Assembly assembly, Assembly startupAsse
mbly, String environment, String startupProjectDir)
at Microsoft.EntityFrameworkCore.Design.MigrationsOperations..ctor(ILoggerProvider loggerProvider, Assembly assembly, AssemblyLoader star
tupAssemblyLoader, Assembly startupAssembly, String environment, String projectDir, String startupProjectDir, String rootNamespace)
at Microsoft.EntityFrameworkCore.Tools.Cli.OperationExecutor.<>c__DisplayClass4_0.<.ctor>b__4()
at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value() at Microsoft.EntityFrameworkCore.Tools.Cli.OperationExecutor.AddMigration(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsAddCommand.Execute(CommonOptions commonOptions, String name, String outputDir, Strin g context, String environment, Action
1 reporter)
at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsAddCommand.<>c__DisplayClass0_0.b__0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
The configuration file 'appsettings.json' was not found and is not optional.
C:_joe__projects__cloudscribe\rc2\cloudscribe.Logging\src\cloudscribe.Logging.EF>
C:_joe__projects__cloudscribe\rc2\cloudscribe.Logging\src\cloudscribe.Logging.EF>dotnet ef migrations add Initial -c LoggingDbContext
Project cloudscribe.Logging.Web (.NETStandard,Version=v1.5) was previously compiled. Skipping compilation.
Project cloudscribe.Logging.EF (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding th
e DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure tha
t your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure1 accessor) at cloudscribe.Logging.EF.LoggingDbContext.OnModelCreating(ModelBuilder modelBuilder) in C:\_joe\__projects\__cloudscribe\rc2\cloudscribe .Logging\src\cloudscribe.Logging.EF\LoggingDbContext.cs:line 41 at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IM odelValidator validator) at System.Collections.Concurrent.ConcurrentDictionary
2.GetOrAdd(TKey key, Func2 valueFactory) at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.LazyRef
1.get_Value()
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.DbContext.get_ChangeTracker()
at cloudscribe.Logging.EF.LoggingDbContext..ctor(DbContextOptions1 options) in C:\_joe\__projects\__cloudscribe\rc2\cloudscribe.Logging\ src\cloudscribe.Logging.EF\LoggingDbContext.cs:line 31 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.EntityFrameworkCore.Design.DbContextOperations.<>c__DisplayClass11_2.<FindContextTypes>b__6() at Microsoft.EntityFrameworkCore.Design.DbContextOperations.CreateContext(Func
1 factory)
at Microsoft.EntityFrameworkCore.Design.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsAddCommand.Execute(CommonOptions commonOptions, String name, String outputDir, Strin
g context, String environment, Action`1 reporter)
at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsAddCommand.<>c__DisplayClass0_0.b__0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method o
r by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a Db
ContextOptions object in its constructor and passes it to the base constructor for DbContext.
C:_joe__projects__cloudscribe\rc2\cloudscribe.Logging\src\cloudscribe.Logging.EF>
public void Map(EntityTypeBuilder<Language> entity)
{
//entity.ToTable(tableNames.TablePrefix + tableNames.LanguageTableName);
entity.ForSqlServerToTable(tableNames.TablePrefix + tableNames.LanguageTableName);
entity.HasKey(p => p.Id);
entity.Property(p => p.Id)
.ForSqlServerHasColumnType("uniqueidentifier")
.ForSqlServerHasDefaultValueSql("newid()")
;
entity.Property(p => p.Name)
.HasMaxLength(255)
.IsRequired()
;
entity.Property(p => p.Code)
.HasMaxLength(2)
.IsRequired()
;
entity.Property(p => p.Sort)
.HasDefaultValue(1)
;
}
migrationBuilder.CreateTable(
name: "cs_Language",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false, defaultValueSql: "newid()"),
Code = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Sort = table.Column<int>(nullable: false, defaultValue: 1)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
},
constraints: table =>
{
table.PrimaryKey("PK_cs_Language", x => x.Id);
});