EF Core Include method not working - entity-framework

I recently updated to asp.net core 2.0. Since upgrading all my Linq queries using Include Method are failing, it is not translated properly to SQL.
For instance this:
var entities = helpTopicRepository.Entities.Include(x => x.HelpArticles).FirstOrDefault(t => topicIds.Any(a => a == t.Id));
is translated to:
SELECT x.HelpArticles.ART_ID,
x.HelpArticles.AVAILABLE,
x.HelpArticles.CONTENT,
x.HelpArticles.DISPLAYORDER,
x.HelpArticles.HELPFULNO,
x.HelpArticles.HELPFULYES,
x.HelpArticles.KEYWORDS,
x.HelpArticles.TITLE,
x.HelpArticles.TOPICID
FROM HELPARTICLE x.HelpArticles
which is results in the following error:
Devart.Data.Oracle.OracleException (0x80004005): ORA-00933: SQL
command not properly ended at Devart.Data.Oracle.ay.b() at
Devart.Data.Oracle.am.f() at Devart.Data.Oracle.am.e() at
Devart.Data.Oracle.c5.a(am A_0, Int32 A_1) at
Devart.Data.Oracle.c5.a(Int32 A_0, bg A_1) at
Devart.Data.Oracle.OracleCommand.InternalExecute(CommandBehavior
behavior, IDisposable disposable, Int32 startRecord, Int32 maxRecords,
Boolean nonQuery) at
Devart.Common.DbCommandBase.ExecuteDbDataReader(CommandBehavior
behavior, Boolean nonQuery) at
Devart.Data.Oracle.Entity.ai.a(CommandBehavior A_0) at
Devart.Common.Entity.cj.d(CommandBehavior A_0) at
Devart.Data.Oracle.Entity.ai.b(CommandBehavior A_0) at
System.Data.Common.DbCommand.ExecuteReader() at
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection
connection, DbCommandMethod executeMethod, IReadOnlyDictionary2
parameterValues) at
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection
connection, IReadOnlyDictionary2 parameterValues) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(Boolean
buffer) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
at
Microsoft.EntityFrameworkCore.Query.Internal.QueryBuffer.IncludeCollection(Int32
includeId, INavigation navigation, INavigation inverseNavigation,
IEntityType targetEntityType, IClrCollectionAccessor
clrCollectionAccessor, IClrPropertySetter inverseClrPropertySetter,
Boolean tracking, Object entity, Func1 relatedEntitiesFactory) at
lambda_method(Closure , QueryContext , Client , Object[] ) at
Microsoft.EntityFrameworkCore.Query.Internal.IncludeCompiler._Include[TEntity](QueryContext
queryContext, TEntity entity, Object[] included, Action3 fixup) at
lambda_method(Closure , Client ) at
System.Linq.Enumerable.SelectEnumerableIterator2.MoveNext() at
System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source)
at lambda_method(Closure , QueryContext ) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass17_0`1.b__0(QueryContext
qc) ORA-00933: SQL command not properly ended
I'm using Devart dotconnect to connect to Oracle database.

Is due to your statement:
var entities = helpTopicRepository.Entities.Include(x => x.HelpArticles).FirstOrDefault(t => topicIds.Any(a => a == t.Id));
Assuming that topicIds is a list, here is a fix:
var entities = helpTopicRepository.Entities
.Include(x => x.HelpArticles)
.Where(t => topicIds.Contains(t.Id))
.FirstOrDefault();

The bug with using multiple .Include() in EF Core 2 is fixed. Look forward to the next public build of dotConnect for Oracle.

Related

Could not load type 'Microsoft.EntityFrameworkCore.Query.RelationalQueryContextFactory' Z.EntityFramework.Plus.EFCore

I have written a simple query which was working when I was using .net core 2.1 (I have used Z.EntityFramework.Plus.EFCore)
int cnt = adminDb.Role.Where(c => c.RoleId == roleId).Delete();
After upgrading to .net core 3.1 I am getting the error below.
Could not load type 'Microsoft.EntityFrameworkCore.Query.RelationalQueryContextFactory' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
Source : Z.EntityFramework.Plus.EFCore
StackTrace : at Z.EntityFramework.Plus.InternalExtensions.GetDbContext[T](IQueryable`1 source)
at Z.EntityFramework.Plus.BatchDelete.Execute[T](IQueryable`1 query)
at Z.EntityFramework.Plus.BatchDeleteExtensions.Delete[T](IQueryable`1 query, Action`1 batchDeleteBuilder)
at Z.EntityFramework.Plus.BatchDeleteExtensions.Delete[T](IQueryable`1 query)
at Assyst.Administration.API.Controllers.RoleMenuMappingController.SavePermission(Nullable`1 roleMenuMasterId, IList`1 roleMenu) in E:\Source\Main_Projects\Application\PanERP-7\Error\Administration\Admin\Controllers\RoleMenuMappingController.cs:line 365
I am receiving this error and I'm not sure what it means?

AspNetCore.Identity using PostgreSQL: how to create structure?

I have a ASP.NET Core web application with AspNetCore.Identity
Logins. It uses SQL Server for user authentication.
I need to use PostgreSQL database I have added some nuget packages (EF.* etc), changed the connection string and code
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
// options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql( Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews()
.AddNewtonsoftJson();
services.AddRazorPages();
}
But when I run it, it connects to the PostgreSQL database and tries to create the structure I receive the error, what is wrong? Why EF cannot create the structure? How to solve this problem?
Executing endpoint 'WebApplication1.Controllers.HomeController.Index (WebA
pplication1)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Index", controller = "Home", page = "", area
= ""}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IAct
ionResult Index() on controller WebApplication1.Controllers.HomeController (WebA
pplication1).
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[1]
Executing ViewResult, running view Index.
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[4]
Executed ViewResult - view Index executed in 302.6169ms.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action WebApplication1.Controllers.HomeController.Index (WebAppli
cation1) in 315.3645ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'WebApplication1.Controllers.HomeController.Index (WebAp
plication1)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 451.9255ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET https://localhost:5001/Identity/Account/Logi
n
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint '/Account/Login'
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[3]
Route matched with {page = "/Account/Login", area = "Identity", action = "
", controller = ""}. Executing page /Account/Login
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[101]
Executing handler method Microsoft.AspNetCore.Identity.UI.V4.Pages.Account
.Internal.LoginModel.OnGetAsync - ModelState is Valid
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[11
]
AuthenticationScheme: Identity.External signed out.
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[102]
Executed handler method OnGetAsync, returned result .
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[103]
Executing an implicit handler method - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[104]
Executed an implicit handler method, returned result Microsoft.AspNetCore.
Mvc.RazorPages.PageResult.
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[4]
Executed page /Account/Login in 104.6291ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint '/Account/Login'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 157.5038ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST https://localhost:5001/Identity/Account/Log
in application/x-www-form-urlencoded 264
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint '/Account/Login'
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[3]
Route matched with {page = "/Account/Login", area = "Identity", action = "
", controller = ""}. Executing page /Account/Login
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[101]
Executing handler method Microsoft.AspNetCore.Identity.UI.V4.Pages.Account
.Internal.LoginModel.OnPostAsync - ModelState is Valid
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 3.1.0 initialized 'ApplicationDbContext' using provi
der 'Npgsql.EntityFrameworkCore.PostgreSQL' with options: None
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (182ms) [Parameters=[#__normalizedUserName_0='?
'], CommandType='Text', CommandTimeout='30']
SELECT a."Id", a."AccessFailedCount", a."ConcurrencyStamp", a."Email", a."
EmailConfirmed", a."LockoutEnabled", a."LockoutEnd", a."NormalizedEmail", a."Nor
malizedUserName", a."PasswordHash", a."PhoneNumber", a."PhoneNumberConfirmed", a
."SecurityStamp", a."TwoFactorEnabled", a."UserName"
FROM "AspNetUsers" AS a
WHERE a."NormalizedUserName" = #__normalizedUserName_0
LIMIT 1
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for cont
ext type 'WebApplication1.Data.ApplicationDbContext'.
Npgsql.PostgresException (0x80004005): 42P01: relation "AspNetUsers" does
not exist
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__Rea
dMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown -
--
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__Rea
dMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown -
--
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsumin
g)
at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Bo
olean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavi
or, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReade
rAsync(RelationalCommandParameterObject parameterObject, CancellationToken cance
llationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReade
rAsync(RelationalCommandParameterObject parameterObject, CancellationToken cance
llationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReade
rAsync(RelationalCommandParameterObject parameterObject, CancellationToken cance
llationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.As
yncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationTok
en cancellationToken)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecuti
onStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 v
erifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.As
yncEnumerator.MoveNextAsync()
Exception data:
Severity: ERROR
SqlState: 42P01
MessageText: relation "AspNetUsers" does not exist
Position: 294
File: parse_relation.c
Line: 1159
Routine: parserOpenTable
Npgsql.PostgresException (0x80004005): 42P01: relation "AspNetUsers" does not ex
ist
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessa
geLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessa
geLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean
async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, Ca
ncellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync
(RelationalCommandParameterObject parameterObject, CancellationToken cancellatio
nToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync
(RelationalCommandParameterObject parameterObject, CancellationToken cancellatio
nToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync
(RelationalCommandParameterObject parameterObject, CancellationToken cancellatio
nToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnu
merator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken can
cellationToken)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStra
tegy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifyS
ucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnu
merator.MoveNextAsync()
Exception data:
Severity: ERROR
SqlState: 42P01
MessageText: relation "AspNetUsers" does not exist
Position: 294
File: parse_relation.c
Line: 1159
Routine: parserOpenTable
info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[4]
Executed page /Account/Login in 2362.999ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint '/Account/Login'
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (18ms) [Parameters=[], CommandType='Text', CommandTimeo
ut='30']
SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_name
space n ON n.oid=c.relnamespace WHERE c.relname='__EFMigrationsHistory');
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 3019.116ms 500 text/html; charset=utf-8
I had to go a bit further than changing the provider and connection string.
In my ApplicationDbContext class:
First, I had an issue with Postgresql wanting to force double-quotes to be added to unquoted identifiers and automatically folding them to lower-case.
PostgreSQL Docs.
My solution was to install the EFCore.NamingConventions package. Then override OnConfiguring as shown below.
Identity 3.0 is apparently expecting the "dbo" schema to be used. Consequently, that needs to be specified by setting the default schema ("public" in this example and that is also the default for Postgresql) by overriding OnModelCreating.
Finally, the database table names need to be lower-cased which is handled by the for loop in the OnModelCreating override.
In the ApplicationDbContext class:
public class ApplicationDbContext
: IdentityDbContext<IdentityUser<int>,IdentityRole<int>,int>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSnakeCaseNamingConvention();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// PostgreSQL uses the public schema by default - not dbo.
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
//Rename Identity tables to lowercase
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
var currentTableName = modelBuilder.Entity(entity.Name).Metadata.GetDefaultTableName();
modelBuilder.Entity(entity.Name).ToTable(currentTableName.ToLower());
}
}
public DbSet<Address> Address { get; set; }
}
After doing this I added a new migration:
add-migration modifyIdentityForPostgresql
Then updated the database schema:
update-database
Which results in the Identity tables being created.
Screen clip of newly created Identity tables in Postgresql
You should run database migration after change provider and connect string , so that the asp.net core identity tables will create in your PostgreSQL database :
Add-Migration InitialCreate
Update-database
Document : https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=vs
My answer is similar to the one that #Steven Tomlinson provided, but in his solution ExampleTableName becomes exampletablename<string>, which I didn't really like as my goal was snake_case.
Create a Helper.cs class
public class Helper
{
public static string ToUnderscoreCase(string str)
{
return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
}
}
Install EFCore.NamingConventions
Edit ApplicationDbContext.cs:
public class ApplicationDbContext
: IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSnakeCaseNamingConvention(); // Not even sure if this is used? it
didn't seem to make any difference
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
var currentTableName = modelBuilder.Entity(entity.Name).Metadata.GetDefaultTableName();
if (currentTableName.Contains("<"))
{
currentTableName = currentTableName.Split('<')[0];
}
modelBuilder.Entity(entity.Name).ToTable(Helper.ToUnderscoreCase(currentTableName));
}
}
}

Multiplicity constraint violated

I have two entites:
ClaimDetail (int ID, IList ClaimDetailStatus, other...)
ClaimDetailStatus (int ID, ClaimDetailClaimDetail, other...)
Configuration:
modelBuilder.Entity<ClaimDetailStatus>()
.HasRequired<ClaimDetail>(x => x.ClaimDetail)
.WithMany(x => x.ClaimDetailStatus)
.HasForeignKey(x => x.ClaimDetailID).WillCascadeOnDelete(true);
modelBuilder.Entity<ClaimDetail>()
.HasMany<ClaimDetailStatus>(x => x.ClaimDetailStatus)
.WithRequired(x => x.ClaimDetail)
.HasForeignKey(x => x.ClaimDetailID).WillCascadeOnDelete(true);
When i'm writing the code, running & debug it everything is fine but when i want to save everything it throws an exception:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Multiplicity constraint violated. The role 'ClaimDetailStatus_ClaimDetail_Target' of the relationship 'EPer.DataAccess.ClaimDetailStatus_ClaimDetail' has multiplicity 1 or 0..1.
Source=System.Data.Entity
StackTrace:
at System.Data.Objects.DataClasses.EntityReference`1.AddToLocalCache(IEntityWrapper wrappedEntity, Boolean applyConstraints)
at System.Data.Objects.EntityEntry.TakeSnapshotOfSingleRelationship(RelatedEnd relatedEnd, NavigationProperty n, Object o)
at System.Data.Objects.EntityEntry.TakeSnapshotOfRelationships()
at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityCollection`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
at System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at EPer.DataAccess.ObjectSetAdapter`1.AddObject(T entity) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.Dal\ObjectSetAdapter.cs:line 41
at EPer.BusinessLogic.DomainServices.ClaimComponent.CreateClaim(Claim claimModel, UserClaim uc) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.BusinessLogic\DomainServices\ClaimComponent.cs:line 28
at EPer.BusinessLogic.ApplicationServices.ClaimService.CreateClaim(Claim claimModel, IEnumerable`1 autoApprovers, UserClaim uc) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.BusinessLogic\ApplicationServices\ClaimService.cs:line 180
at EPer.BusinessLogic.ApplicationServices.ClaimService.CreateClaim(Claim claimModel, IEnumerable`1 autoApprovers) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.BusinessLogic\ApplicationServices\ClaimService.cs:line 113
at EPer.BusinessLogic.ApplicationServices.ClaimService.CreateClaim(Claim claimModel) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.BusinessLogic\ApplicationServices\ClaimService.cs:line 99
at EPer.Areas.Claims.Controllers.ClaimController.Create(SingleClaim m) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer\Areas\Claims\Controllers\ClaimController.cs:line 107
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException:
Generated association:
<Association Name="ClaimDetailStatus_ClaimDetail">
<End Role="ClaimDetailStatus_ClaimDetail_Source" Type="Self.ClaimDetailStatus" Multiplicity="*" />
<End Role="ClaimDetailStatus_ClaimDetail_Target" Type="Self.ClaimDetail" Multiplicity="1">
<OnDelete Action="Cascade" />
</End>
<ReferentialConstraint>
<Principal Role="ClaimDetailStatus_ClaimDetail_Target">
<PropertyRef Name="ID" />
</Principal>
<Dependent Role="ClaimDetailStatus_ClaimDetail_Source">
<PropertyRef Name="ClaimDetailID" />
</Dependent>
</ReferentialConstraint>
I have checked the generated visualized Entity Data Model and everything looked okay.
What is happening here?
EDIT correction
I have a 3rd entity: Claim; if a Claim contains only one ClaimDetail everything works fine but if it contains 2 ClaimDetail the above exception is thrown.
The problem was that i added to each of the ClaimDetail's ClaimDetailStatus collection the same instance of the first ClaimDetailStatus. If i'm adding different instances (in a cycle detail.ClaimDetailStatus.Add(new ...)) everything works fine.
ClaimDetail (int ID, IList ClaimDetailStatus, other...)
ClaimDetailStatus (int ID, ClaimDetailClaimDetail, other...)
This happened when I got entity from db, then tried to save the edited one.
Try
Detached ClaimDetail.ClaimDetailStatus.ClaimDetailClaimDetail,
ClaimDetail.ClaimDetailStatus,
ClaimDetail
Then save, it works.

NullReferenceException with EF6 on Mono 3.0.3

I am trying to migrate existing Entity Framework project to Mono and found a strange bug: when request being executed and EF loads model schema it throws under Mono despite that under .Net with EF6 Alpha 2 it works. An exception is following:
at System.Xml.XmlReader.CalcBufferSize(Stream input)
at System.Xml.XmlTextReaderImpl.InitStreamInput(Uri baseUri, String baseUriStr, Stream stream, Byte[] bytes, Int32 byteCount, Encoding encoding)
at System.Xml.XmlTextReaderImpl..ctor(String url, Stream input, XmlNameTable nt)
at System.Xml.XmlTextReader..ctor(Stream input)
at System.Xml.Schema.XmlSchema.Read(Stream stream, ValidationEventHandler validationEventHandler)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.AddXmlSchemaToSet(XmlSchemaSet schemaSet, XmlSchemaResource schemaResource, HashSet`1 schemasAlreadyAdded)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.AddXmlSchemaToSet(XmlSchemaSet schemaSet, XmlSchemaResource schemaResource, HashSet`1 schemasAlreadyAdded)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.ComputeSchemaSet(SchemaDataModelOption dataModel)
at System.Data.Entity.Core.Common.Utils.Memoizer`2.<Evaluate>c__AnonStorey106.<>m__100()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.GetSchemaSet(SchemaDataModelOption dataModel)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.CreateXmlReaderSettings()
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.Parse(XmlReader sourceReader, String sourceLocation)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, AttributeValueNotification providerNotification, AttributeValueNotification providerManifestTokenNotification, ProviderManifestNeeded providerManifestNeeded, IList`1& schemaCollection)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader.LoadItems(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, Boolean throwOnError)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerManifestToken, Memoizer`2& cachedCTypeFunction)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.StoreMetadataEntry.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.StoreItemCollectionLoader.LoadItemCollection(StoreMetadataEntry entry)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadItemCollection[T](IItemCollectionLoader`1 itemCollectionLoader, T entry)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetOrCreateStoreAndMappingItemCollections(String cacheKey, MetadataArtifactLoader loader, EdmItemCollection edmItemCollection, Object& entryToken)
at System.Data.Entity.Core.EntityClient.EntityConnection.LoadStoreItemCollections(MetadataWorkspace workspace, DbConnection storeConnection, DbConnectionOptions connectionOptions, EdmItemCollection edmItemCollection, MetadataArtifactLoader artifactLoader)
at System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)
at System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace()
at System.Data.Entity.Core.EntityClient.EntityConnection.InitializeMetadata(DbConnection newConnection, DbConnection originalConnection, Boolean closeOriginalConnectionOnFailure)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<GetEnumerator>m__2C3()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction`1>m__29A[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression)
I guess it cannot load metadata or something like that, at least deapest lines looks like known behaviour of XmlDocument and XmlSchema when they do not check that input stream is null. I tried to use metadata files instead of embedded resources, but it did not help.
I will try to digg into sources, but it would be really helpful if someone already have idea what is going on.
You are running quite unusual configuration, EF compiled by Mono and System.XML from .NET Framework. This itself should work if System.XML can deal with the location of your schema but it's not common configuration.
I'd check how is the schema embedded into your assembly and whether is using same namespace.

MVC3 EE CTP - Format of the initialization string does not conform to specification starting at index 0

I have small MVC 3 Entity code first application, I created table in my local database and took the backup of table and restored the data on winhost web hosting database.
In my web.config I have change connection string to winhost connection starting. it wrosk on my desktop.
I transferred my local application to windows, when access the application I am getting this error.
error coming from this method.
public ActionResult ListRecords()
{
var query = from e in db.Envelopes
orderby e.ReportDate descending
select e;
IEnumerable<Envelopes> top10 = query.Take(25);
return View(top10.ToList<Envelopes>());
}
Error message:
Format of the initialization string does not conform to specification starting at index 0.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Format of the initialization string does not conform to specification starting at index 0.]
System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) +5025863
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +132
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +98
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +64
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +24
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +150
System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value) +59
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +4
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name) +399
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +49
System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel() +10
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +252
System.Data.Entity.Internal.InternalContext.Initialize() +16
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +61
System.Data.Entity.Internal.Linq.InternalSet`1.get_Provider() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +13
System.Linq.Queryable.OrderByDescending(IQueryable`1 source, Expression`1 keySelector) +66
Envelopesonly.Controllers.HomeController.ListRecords() in HomeController.cs:84
lambda_method(Closure , ControllerBase , Object[] ) +40
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +188
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +267
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +190
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +329
System.Web.Mvc.Controller.ExecuteCore() +115
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +94
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +31
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +23
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +59
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
Any help fixing this error?
Thanks
SR
Why are you still using the CTP? The release has been out for quite some time. Upgrade, then see if your problem persists. It may be a fixed problem.
The stack trace points out that there is a problem with your connection string.
Fix your connection string, and the problem should dissapear.