EFCore.BulkExtensions fails to do insert with Guid PK - entity-framework

I am using EFCore.BulkExtensions to insert an entity with a GUID / UniqueIdentifier primary key into my database, but I am receiving the following exception when I call this line:
System.InvalidOperationException HResult=0x80131509 Message=The
given value of type String from the data source cannot be converted to
type uniqueidentifier of the specified target column.
Source=EFCore.BulkExtensions StackTrace: at
EFCore.BulkExtensions.SqlBulkOperation.Insert[T](DbContext context,
IList1 entities, TableInfo tableInfo, Action1 progress) at
EFCore.BulkExtensions.DbContextBulkExtensions.BulkInsert[T](DbContext
context, IList1 entities, BulkConfig bulkConfig, Action1 progress)
at
MyCompany.Abp.EfCore.BulkExtensions.BulkInsert[TEntity,TPrimaryKey](IRepository2
repository, IList1 entities, BulkConfig bulkConfig, Action1
progress) in
D:\Projects\MySystem\Utilities\MyCompany.Abp.EfCore\BulkExtensions.BulkInsert.cs:line
21 at
s.SearchServices.Infrastructure.UnscConsolidatedList.Infrastructure.s.MonitoringBatch.MonitoringBatchSearchJob.PerformScreening(Guid
sourceId, IList1 Records) in
D:\Projects\MySystem\Modules\s\s.SearchServices.Infrastructure.UnscConsolidatedList\Infrastructure\s\MonitoringBatch\MonitoringBatchSearchJob.cs:line
96 at
s.SearchServices.Infrastructure.UnscConsolidatedList.Infrastructure.s.MonitoringBatch.MonitoringBatchSearchJob.ExecuteJob(MonitoringBatchSearhJobArgs
args) in
D:\Projects\MySystem\Modules\s\s.SearchServices.Infrastructure.UnscConsolidatedList\Infrastructure\s\MonitoringBatch\MonitoringBatchSearchJob.cs:line
82 at
s.SearchServices.Infrastructure.UnscConsolidatedList.Core.BatchSearchJobBase`1.Execute(TBatchSearhJobArgs
args) in
D:\Projects\MySystem\Modules\s\s.SearchServices.Infrastructure.UnscConsolidatedList\Core\BatchSearchJobBase.cs:line
28
Inner Exception 1: InvalidCastException: Failed to convert parameter
value from a String to a Guid.
Inner Exception 2: InvalidCastException: Invalid cast from
'System.String' to 'System.Guid'.
The code that throws the exception:
public static void BulkInsert<TEntity, TPrimaryKey>(
this IRepository<TEntity, TPrimaryKey> repository,
IList<TEntity> entities,
BulkConfig bulkConfig = null,
Action<decimal> progress = null)
where TEntity : class, IEntity<TPrimaryKey>
{
var db = repository.GetDbContext();
db.BulkInsert(entities, bulkConfig, progress); // <== throws exception
}
What am I doing wrong?

Related

How to use #BeforeStep Job Parameters in JdbcCursorItemReader for named Query

I have the code like below
#Bean
public JdbcCursorItemReader<Map<String, Object>> itemReader() {
return new JdbcCursorItemReader<Map<String, Object>>() {
private JobParameters jobParameter;
String sql = "select EMPLOYEE_ID as empId, EMPLOYEE_NAME as empName EMPLOYEE_AGE as age from EMPLOYEE EMPLOYEE_DEPT =:empDept and EMPLOYEE_SAL > :empSal";
Map<String, Object> namedParameters = null;
#PostConstruct
public void initialize() throws Exception
{
setDataSource(dataSource);
setSql("select 1 from dual");
setRowMapper(new ColumnMapRowMapper());
}
#BeforeStep
public void retrieveExecutionContext(StepExecution stepExecution)
{
jobParameter = stepExecution.getJobParameters();
namedParameters = new HashMap<String, Object>() {
{
put("bstd", jobParameter.getString("empDept"));
put("bwtn", jobParameter.getString("empSal"));
}
};
jobParameter.getParameters().forEach((k, v) -> System.out.println("key =" + k + ", Value:" + v));
}
#Override
public void afterPropertiesSet() throws Exception {
setSql(NamedParameterUtils.substituteNamedParameters(sql, new MapSqlParameterSource(namedParameters)));
setPreparedStatementSetter(new ListPreparedStatementSetter(
Arrays.asList(NamedParameterUtils.buildValueArray(sql, namedParameters))));
setRowMapper(new ColumnMapRowMapper());
setDataSource(dataSource);
super.afterPropertiesSet();
}
};
}
Tried using calling afterPropertiesSet, but still seeing below exception
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'empDept': No value registered for key 'empDept'
at org.springframework.jdbc.core.namedparam.NamedParameterUtils.buildValueArray(NamedParameterUtils.java:361) ~[spring-jdbc-5.3.22.jar:5.3.22]
at org.springframework.jdbc.core.namedparam.NamedParameterUtils.buildValueArray(NamedParameterUtils.java:485) ~[spring-jdbc-5.3.22.jar:5.3.22]
Requirement is dynamic query, so don't have control of the Select query and the where conditions.
Thanks in advance,
You can use a SpEL expression to inject and use job parameters in your item reader bean definition as follows:
#Bean
#StepScope
public JdbcCursorItemReader<Map<String, Object>> itemReader(#Value("#{jobParameters['empDept']}") String empDept, #Value("#{jobParameters['empSal']}") String empSal) {
JdbcCursorItemReader<Map<String, Object>> itemReader = new JdbcCursorItemReader<>();
// use parameters 'empDept' and 'empSal' in your sql query as needed
return itemReader;
}
Note that the item reader should be step-scoped for that to work. For more details, please refer to the documentation: Late Binding of Job and Step Attributes.

java.lang.NullPointerException occur upon execution

Null pointer exception occurs when you reference a null object, doesn't it? I intend to create an app that manages a store's data such as purchase (stock purchase), stock list, sales, and customer info. The data is intended to be displayed on the app table as soon as the file dynamicmenu1 is run, without clicking any button, but it only displays hard-coded data instead.
app interface
Data to be displayed from table
at view.dynamicmenu1.simpannotaActionPerformed(dynamicmenu1.java:984)
at view.dynamicmenu1.access$1000(dynamicmenu1.java:37)
at view.dynamicmenu1$11.actionPerformed(dynamicmenu1.java:404)
private void simpannotaActionPerformed(java.awt.event.ActionEvent evt) {
tabmodel.addRow(data); // line 984
try {
/** con = (Connection) Model.koneksidatabase();
java.sql.PreparedStatement prepstmnt = con.prepareStatement(sql);
*/
Statement stmnt = con.createStatement();
String sql = "Insert into tb_pembelian VALUES ('" + textid.getText()+"','"
+textnamabrg.getText()+"','"+textqty.getText()
+"','"+texthrg.getText()+"','"+texttgl.getText()+"','"+textsupplier.getText();
//cek stmnt di 'Model.java' di bagian ArrayList barang().
//Mengapa selalu Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
//at view.dynamicmenu1.simpannotaActionPerformed(dynamicmenu1.java:960)
//at view.dynamicmenu1.access$900(dynamicmenu1.java:21)
//at view.dynamicmenu1$10.actionPerformed(dynamicmenu1.java:378)??????
//NullPointerException??????
stmnt.executeUpdate(sql);
stmnt.close();
JOptionPane.showMessageDialog(null, "Data telah disimpan");
kosongkanform();
} catch ( HeadlessException| SQLException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
textid.setText("");
textnamabrg.setText("");
textqty.setText("");
texthrg.setText("");
texttgl.setText("");
textsupplier.setText("");
}
// line 37
public class dynamicmenu1 extends javax.swing.JFrame {
String id_barang;
String nama_barang;
String kuantitas;
String harga_satuan;
String tanggal_beli;
DefaultTableModel tabmodel;
Connection con =null;
Statement stmnt=null;
PreparedStatement prepstmnt;
ResultSet res = null;
String sql = null;
the 3rd null pointer exception error
simpannota.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
simpannotaActionPerformed(evt); // Line 404
}
});
Null pointer errors happen when there isn't anything present.
Have you checked your constructor for proper init for your variables.

Asp.net core rc1, dbcontext connection is closed in IStringLocalizer GetString method

Asp.net core rc1, dbcontext connection is closed in IStringLocalizer GetString method. Happening only when VS2015 is on Debug mode and only once at start up.
I am using Autofac DI, but same issue (without autofac) using the buildin DI.
When I am running the App in debug mode and only at start up, producing the following error. When I refresh the browser all fine, no errors. If I run the App without debugging, no errors, everything runs normally.
Something's wrong with the debugging threat and the DI? Any ideas?
Error on browser:
A database operation failed while processing the request.
InvalidOperationException: ExecuteReader requires an open and
available Connection. The connection's current state is closed.
Output window:
Microsoft.Data.Entity.Storage.Internal.RelationalCommandBuilderFactory: Information: Executed DbCommand (55ms) [Parameters=[#___cultureName_0='?', #__name_1='?'], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [l].[CultureId], [l].[Name], [l].[Value]
FROM [UIResources] AS [l]
WHERE ([l].[CultureId] = #___cultureName_0) AND ([l].[Name] = #__name_1)
Microsoft.Data.Entity.Query.Internal.QueryCompiler: Error: An exception occurred in the database while iterating the results of a query.
System.NullReferenceException: Not Specified object reference to an instance object.
σε System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
σε System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
σε System.Data.SqlClient.SqlConnection.Open()
σε Microsoft.Data.Entity.Storage.RelationalConnection.Open()
σε Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
σε System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
σε System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
σε lambda_method(Closure , QueryContext )
σε Microsoft.Data.Entity.Query.Internal.QueryCompiler.<>c__DisplayClass18_1`1.<CompileQuery>b__1(QueryContext qc)
Microsoft.Data.Entity.Query.Internal.QueryCompiler: Error: An exception occurred in the database while iterating the results of a query.
System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.<>c__DisplayClass17_0.<ExecuteReader>b__0(DbCommand cmd, IRelationalConnection con)
at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.Execute[T](IRelationalConnection connection, Func`3 action, String executeMethod, Boolean openConnection, Boolean closeConnection)
at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, Boolean manageConnection)
at Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at lambda_method(Closure , QueryContext )
at Microsoft.Data.Entity.Query.Internal.QueryCompiler.<>c__DisplayClass18_1`1.<CompileQuery>b__1(QueryContext qc)
Exception thrown: 'System.NullReferenceException' in EntityFramework.Core.dll
Exception thrown: 'System.InvalidOperationException' in EntityFramework.Core.dll
This is my startup:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc().AddViewLocalization();
services.AddMvc().AddDataAnnotationsLocalization();
services.AddLocalization();
// Create the Autofac container builder.
var builder = new ContainerBuilder();
// Populate the services from the collection.
// This have to come First.
builder.Populate(services);
// Register dependencies.
builder.RegisterType<AuthMessageSender>().As<IEmailSender>().InstancePerLifetimeScope();
builder.RegisterType<AuthMessageSender>().As<ISmsSender>().InstancePerLifetimeScope();
builder.RegisterType<DataInitializer>().As<IDataInitializer>().InstancePerLifetimeScope();
builder.RegisterType<CultureHelper>().As<ICultureHelper>().InstancePerLifetimeScope();
builder.RegisterType<RouteRequestCultureProvider>().InstancePerLifetimeScope();
builder.RegisterType<CultureActionFilter>().InstancePerLifetimeScope();
builder.RegisterType<DbStringLocalizerFactory>().As<IStringLocalizerFactory>().InstancePerLifetimeScope();
// DbStringLocalizer registers with InstancePerDependency,
// because localization requires a new instance of IStringLocalizer created in the IStringLocalizerFactory.
builder.RegisterType<DbStringLocalizer>().As<IStringLocalizer>().InstancePerDependency();
// Build the container.
var container = builder.Build();
// Return the IServiceProvider resolved from the container.
return container.Resolve<IServiceProvider>();
}
This is Localization implementation:
public class DbStringLocalizerFactory : IStringLocalizerFactory
{
private IServiceProvider _serviceProvider;
public DbStringLocalizerFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IStringLocalizer Create(Type resourceSource)
{
return _serviceProvider.GetService<IStringLocalizer>();
}
public IStringLocalizer Create(string baseName, string location)
{
return _serviceProvider.GetService<IStringLocalizer>();
}
}
public class DbStringLocalizer : IStringLocalizer
{
private ApplicationDbContext _db;
private string _cultureName;
public DbStringLocalizer(ApplicationDbContext db)
: this(db, CultureInfo.CurrentCulture)
{
}
public DbStringLocalizer(ApplicationDbContext db, CultureInfo cultureInfo)
{
_db = db;
_cultureName = cultureInfo.Name;
}
public LocalizedString this[string name]
{
get
{
var value = GetString(name);
return new LocalizedString(name, value ?? name, resourceNotFound: value == null);
}
}
public LocalizedString this[string name, params object[] arguments]
{
get
{
var format = GetString(name);
var value = string.Format(format ?? name, arguments);
return new LocalizedString(name, value, resourceNotFound: format == null);
}
}
private string GetString(string name)
{
//try
//{
var query = _db.UIResources.Where(l => l.CultureId == _cultureName);
var value = query.FirstOrDefault(l => l.Name == name);
return value?.Value;
//}
//catch
//{
// return null;
//}
}
public IEnumerable<LocalizedString> GetAllStrings(bool includeAncestorCultures)
{
return _db.UIResources.Where(l => l.CultureId == _cultureName)
.Select(l => new LocalizedString(l.Name, l.Value, true));
}
public IStringLocalizer WithCulture(CultureInfo culture)
{
return new DbStringLocalizer(_db, culture);
}
}
The IDataInitializer registration as scoped service in
builder.RegisterType<DataInitializer>().As<IDataInitializer>().InstancePerLifetimeScope();
seems odd, as a data initializer is expected to be called only once, when the application starts to ensure the database is created and filled with data required to run the application or after an update.
I suspect you dispose the scoped db context somewhere inside your DataInitializer class, so it becomes unavailable during your request because your IoC container will always return the same instance for the duration of the request.

.NET 4.5 SessionAuthenticationModule - Issue with "validFrom"

I'm using SWT in Windows Azure ACS and custom SwtHandler is used in Relying Party applicaiton to handle incoming SWT token. While it re-creates the SWT token at relying party, I get an error with creation of SessionSecurityToken related to value of validFrom attribute.
I've tried out following values for ValidFrom, but didn't fix the problem.
DateTime SwtBaseTime = new DateTime( 1970, 1, 1, 0, 0, 0, 0 );
DateTime.UtcNow
DateTime.MinValue
Specified argument was out of the range of valid values.
Parameter name: validFrom
[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: validFrom]
System.IdentityModel.Tokens.SessionSecurityToken..ctor(ClaimsPrincipal claimsPrincipal, UniqueId contextId, String id, String context, Byte[] key, String endpointId, Nullable1 validFrom, Nullable1 validTo, UniqueId keyGeneration, Nullable1 keyEffectiveTime, Nullable1 keyExpirationTime, SctAuthorizationPolicy sctAuthorizationPolicy, Uri securityContextSecurityTokenWrapperSecureConversationVersion) +1009610
System.IdentityModel.Tokens.SessionSecurityToken..ctor(ClaimsPrincipal claimsPrincipal, UniqueId contextId, String context, String endpointId, Nullable1 validFrom, Nullable1 validTo, SymmetricSecurityKey key) +317
System.IdentityModel.Tokens.SessionSecurityTokenHandler.CreateSessionSecurityToken(ClaimsPrincipal principal, String context, String endpointId, DateTime validFrom, DateTime validTo) +306
System.IdentityModel.Services.SessionAuthenticationModule.CreateSessionSecurityToken(ClaimsPrincipal principal, String context, DateTime validFrom, DateTime validTo, Boolean isPersistent) +313
System.IdentityModel.Services.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequestBase request) +1079
System.IdentityModel.Services.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args) +123924
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
I ran into a similar problem recreating the session security token while trying to implement sliding expiration for the SessionAuthenticationModule.
protected void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
DateTime now = DateTime.UtcNow;
DateTime validFrom = e.SessionToken.ValidFrom;
DateTime validTo = e.SessionToken.ValidTo;
TimeSpan sessionLifetime = validTo.Subtract(e.SessionToken.ValidFrom);
bool sessionTimeHasExpired = now > validTo;
bool sessionTimeIsHalfExpired = now > validFrom.AddMinutes(sessionLifetime.TotalMinutes / 2);
// http://www.michael-mckenna.com/Blog/2013/2/the-problem-with-absolute-token-expiration-in-windows-identity-foundation-wif
if (!sessionTimeHasExpired && sessionTimeIsHalfExpired)
{
// If the session has not expired but the session lifetime is already half spent, reissue the cookie.
e.SessionToken = (sender as SessionAuthenticationModule).CreateSessionSecurityToken(e.SessionToken.ClaimsPrincipal, e.SessionToken.Context,
now, now.AddMinutes(sessionLifetime.TotalMinutes), e.SessionToken.IsPersistent);
e.ReissueCookie = true;
}
}
The CreateSessionSecurityToken method takes a value for validFrom and validTo. If these two values are equal, it throws an ArgumentOutOfRange exception.
I ran into the problem because originally I was using sessionLifetime.Minutes (which was 0) rather than sessionLifetime.TotalMinutes (which was 100).
Try using the same KeyEffectiveTime
e.SessionToken = sam.CreateSessionSecurityToken(
e.SessionToken.ClaimsPrincipal,
e.SessionToken.Context,
e.SessionToken.KeyEffectiveTime,
e.SessionToken.KeyExpirationTime.AddHours(8),
e.SessionToken.IsPersistent);

CREATE DATABASE permission denied in database 'master' Entity Framework Migration

I am trying to deploy an ASP.NET MVC 4 application with Entity Framework 4.4 to a shared web hosting (GoDaddy-4GH platform). In GoDaddy I can't create databases using the application code I have to create it via their control panel, which I did.
I want to use the migration feature to allow my database to evolve without manually modify the schema.
I've use a combination of IDatabaseInitializer and DbMigrationsConfiguration. The db initializer simply migrates to the latest version.
The problem is that during the update process EF checks whether the database exists using the EnsureDatabaseExists method, and if for some reason it decides that is does not, then it goes ahead and tries to create a new database which of course fails.
How can I debug why the EnsureDatabaseExists returns false?
Is it possible to override this behavior? (from looking at the code with reflection it does not seem that way)
DBMigration implementation
public class DBMigrationInitializaer : IDatabaseInitializer<AppDbContext> {
public void InitializeDatabase(AppDbContext context) {
bool dbExists;
var mig = new DbMigrator(new MigrationConfiguration());
mig.Update();
Seed(context);
context.SaveChanges();
}
protected virtual void Seed(AppDbContext context) {
// TODO: put here your seed creation
}
Exception stack trace
[SqlException (0x80131904): CREATE DATABASE permission denied in database 'master'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +2072894
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5061932
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) +228
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +326
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +137
System.Data.SqlClient.<>c__DisplayClassa.<DbCreateDatabase>b__7(SqlConnection conn) +38
System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act) +98
System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act) +349
System.Data.SqlClient.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +315
System.Data.Objects.ObjectContext.CreateDatabase() +84
System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +73
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists() +76
System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +44
System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update() +12
MvcApplication1.Models.MyDBInitializaer.InitializeDatabase(AppContext context) in MyDBInitializaer.cs:31
System.Data.Entity.<>c__DisplayClass2`1.<SetInitializerInternal>b__0(DbContext c) +75
System.Data.Entity.Internal.<>c__DisplayClass8.<PerformDatabaseInitialization>b__6() +19
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +72
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +186
System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c) +7
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +118
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +190
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +73
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +28
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +56
System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +40
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +315
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
MvcApplication1.Controllers.EmployeeController.Index() in EmployeeController.cs:21
Thank you,
Ido
I have the same problem with my webhost (amen.fr). During SEVERAL days I looked and I realized that there's something in the implementation of the class DBMigrator and sql server configuring at the host which causes this dysfunction. "System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists" unable to check the correct information. That why all transactions with the database are made with my data context. Here is the code that allows me to make semi-automatic migration :
public class Migrator
{
public static void RunMigrations()
{
//Configuration configuration = new Configuration();
//configuration.ContextType = typeof(BOContext);//TODO Change to your DbContext
//configuration.MigrationsAssembly = configuration.ContextType.Assembly;
//configuration.MigrationsNamespace = "BO.Domain.Migrations";//TODO Namespace that contains your migrations classes
//configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");
//DbSeederMigrator<BOContext> migrator = new DbSeederMigrator<BOContext>(configuration);
//migrator.MigrateToLatestVersion();
using (BOContext context = new BOContext())
{
Configuration configuration = new Configuration();
configuration.ContextType = typeof(BOContext);//TODO Change to your DbContext
configuration.MigrationsAssembly = configuration.ContextType.Assembly;
configuration.MigrationsNamespace = "CodeFirstMembershipSharp.Migrations";//TODO Namespace that contains your migrations classes
configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");
DbMigrator migrator = new DbMigrator(configuration);
MigratorScriptingDecorator scriptor = new MigratorScriptingDecorator(migrator);
var lm = migrator.GetLocalMigrations();// get local migration
var dm = context.Database.SqlQuery<Migration>("select MigrationId from dbo.__MigrationHistory").Select(o => o.MigrationId); // get database migration
List<string> pm = lm.Except(dm).ToList();// buil and set pending migration
if (pm.Any())// Peding migration exists
{
string source = dm.Any() ? dm.OrderBy(o => o).Last() : DbMigrator.InitialDatabase;// get last to set source migration
string target = pm.OrderBy(o => o).Last(); /// gest last to set target migration
string sql = scriptor.ScriptUpdate(source, target); // buit sql script migration
try { context.Database.ExecuteSqlCommand(sql); } // execute sql script migration
catch (Exception e)
{
string spm = "Pending migrations : " + String.Join(";", pm.ToArray());
string sdm = "Database migrations : " + String.Join(";", pm.ToArray());
string[] tmp = { e.Message, spm, sdm, "Source : " + source, "Target : " + target, sql };
throw new Exception(String.Join("\n-----------------\n", tmp));
}
}
}
//// TODO : code seed here
//Migrator.Seed();
}
protected static void Seed()
{
//using (BOContext context = new BOContext())
//{
// if (!context.Users.Any())
// {
// MembershipCreateStatus Status;
// Membership.CreateUser("Demo", "123456", "demo#demo.com", null, null, true, out Status);
// if (!context.Roles.Any(o => o.RoleName == "Admin"))
// {
// Roles.CreateRole("Admin");
// Roles.AddUserToRole("Demo", "Admin");
// }
// }
//}
}laguna-veneta
}