Quantcast
Channel: Entity Framework
Viewing all 10318 articles
Browse latest View live

Commented Unassigned: Build and BuildEFTools does not generate .nupkg and .msi [2443]

$
0
0
Dear,

I cloned the entity framework git repository to get debugging support which I need to analyse some problems during my development. After cloning the repository I worked through

https://entityframework.codeplex.com/wikipage?title=Getting%20and%20Building%20EF%20Runtime and
https://entityframework.codeplex.com/wikipage?title=Getting%20and%20Building%20EF%20Tools

The dlls, pdbs and xml files are created as expected (some unit tests failed because of naming conventions with my sql server instance but I do not need to run the unit tests), but the nuget package and the msi installer is not created for me.

Because I am not reliant on nuget, this is not a problem for me. But i am using code first migrations, which needs the Enable-Migrations, Add-Migrations and Update-Database commands to be available on the nuget package manager console (I found no solution to run this comments from a c# application).

The libraries I can use normally without the msi and without the nuget package, but actually I haven't any idea on how to make the code first migrations run for me. Could you please advice me on integrate this commands?

Kind regards,
Sebastian.
Comments: Howdy Sebastian, Here are some answers. 1. No, you may reference the dlls directly. The NuGet package just takes care of adding some things to your App or Web.config. It also includes the Package Management Console integration for Code First Migrations. 2. The typical way to do this with NuGet packages is to use the SymbolSource.org integration. We've tried to provide this special symbols package, but there were issues with symbolsource we weren't ever able to get resolved. I believe we still have a workitem to follow up on this. As an alternative, you can manually copy the pdbs next to the dlls under your project's packages/EntityFramework.*/lib directory. 3. Yes. Please see [my answer to a StackOverflow question of the same](http://stackoverflow.com/a/20382226/475031). You can also attach the debugger to the commands by attaching to devenv.exe--the Visual Studio instance in which you'll be running the commands. 4. I don't know that I have any specific answer for this. Debugging is a good way to understand what EF is doing behind the scenes. If you find any unexpected behavior, please file a bug and we'd be happy to investigate. Let me know if I can provide any additional help. -Brice

Commented Unassigned: Build and BuildEFTools does not generate .nupkg and .msi [2443]

$
0
0
Dear,

I cloned the entity framework git repository to get debugging support which I need to analyse some problems during my development. After cloning the repository I worked through

https://entityframework.codeplex.com/wikipage?title=Getting%20and%20Building%20EF%20Runtime and
https://entityframework.codeplex.com/wikipage?title=Getting%20and%20Building%20EF%20Tools

The dlls, pdbs and xml files are created as expected (some unit tests failed because of naming conventions with my sql server instance but I do not need to run the unit tests), but the nuget package and the msi installer is not created for me.

Because I am not reliant on nuget, this is not a problem for me. But i am using code first migrations, which needs the Enable-Migrations, Add-Migrations and Update-Database commands to be available on the nuget package manager console (I found no solution to run this comments from a c# application).

The libraries I can use normally without the msi and without the nuget package, but actually I haven't any idea on how to make the code first migrations run for me. Could you please advice me on integrate this commands?

Kind regards,
Sebastian.
Comments: The SymbolSource issue is [Work Item 386](https://entityframework.codeplex.com/workitem/386).

Commented Unassigned: TypesMatchByConvention NullReferenceException [2466]

$
0
0
I'm getting a NullReferenceException out of TypesMatchByConvention.

I've built a sample application from the same database that's having trouble and the sample application works fine, so I believe the problems have to do with upgrading from EF 4 to EF 6, but it's really hard to track down a bug from a NullReferenceException :/
Comments: I will not be able to attach my code because it is proprietary but I can talk about it. I dug backwards through the stack trace and I'm pretty sure the only variable that could be null is the type.BaseType variable in TypesMatchByConvention which looks like it's populated by a method called by LoadTypesFromAssembly() that I couldn't find. I'm working with someone on the azure forum and he says it looks like my metadata wasn't regenerated properly...the thing is I have rebuilt my model from scratch using the EF6 tools. I built the model in a sample project using the EF6 tools and that project works, so it has to do with the migration. Here is my stack trace except for my methods at the bottom of the trace. Let me know what questions you have. Like I said, I can talk about the process I used in general but I can't share code. at System.Data.Entity.Core.Metadata.Edm.OSpaceTypeFactory.TypesMatchByConvention(Type type, EdmType cspaceType) at System.Data.Entity.Core.Metadata.Edm.OSpaceTypeFactory.TryCreateStructuralType(Type type, StructuralType cspaceType, EdmType& newOSpaceType) at System.Data.Entity.Core.Metadata.Edm.OSpaceTypeFactory.TryCreateType(Type type, EdmType cspaceType) at System.Data.Entity.Core.Metadata.Edm.ObjectItemConventionAssemblyLoader.LoadTypesFromAssembly() at System.Data.Entity.Core.Metadata.Edm.ObjectItemAssemblyLoader.Load() at System.Data.Entity.Core.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData) at System.Data.Entity.Core.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors) at System.Data.Entity.Core.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage) at System.Data.Entity.Core.Metadata.Edm.ObjectItemCollection.ExplicitLoadFromAssembly(Assembly assembly, EdmItemCollection edmItemCollection, Action`1 logLoadMessage) at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.ExplicitLoadFromAssembly(Assembly assembly, ObjectItemCollection collection, Action`1 logLoadMessage) at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadFromAssembly(Assembly assembly, Action`1 logLoadMessage) at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadFromAssembly(Assembly assembly) at System.Data.Entity.Internal.InternalContext.TryUpdateEntitySetMappingsForType(Type entityType) at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType) at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() at System.Linq.Queryable.Count[TSource](IQueryable`1 source)

Commented Issue: Upgrading EF 6.0.2 -> EF6.1.0 Create Indexes [2167]

$
0
0
After upgrading from EF 6.0.2 to 6.1.0 my database is no longer compatible with current model.
When adding a migration EF wants to create all indexes. I have worked around this by first deleting all indexes (took this code from the down method) and creating them.
This fixed the issue. Not sure if this is by design, i couldn't find an upgrade guide to 6.1.

Thought i'd let you know.
Comments: This issue is still happening in 6.1.1. The latest migration in my DB was generated by 6.0.2 and so the model didn't contain indexes. A newly created database had that model information. Initial creation was successful and I could connect and query the DB, but the second connection failed with AutomaticMigrationsDisabledException. My solution was to create a new migration, even though there were no changes. EF "detected" that some indexes were missing, and generated Up/Down code. I deleted that code, but now the model of the latest migration contained the index info. Now everything works.

Created Unassigned: Support custom equality for complex types (value objects) [2473]

$
0
0
We have value objects that define custom equality semantics, following standard Domain Driven Design semantics. These are mapped as "complex types" in entity framework terminology.

Unfortunately, entity framework ignores these custom equality operators, and instead detects erroneous changes in the change tracker whenever the Value Object _instance_ is changed, even if they are logically equivalent, and even when there would be absolutely no change of values in the mapped database fields.

The workarounds for this are ugly - and I don't have one yet that is 100% reliable. Looping through the change tracker entries is tedious, and I haven't (yet anyway) found a 100% reliable way to deal with this in a sufficiently generic fashion by looping through the change tracker entries.

Entity framework should allow me to specify that for specific types, the type's _own_ equality operators are used for detecting changes in values.


Commented Feature: Better auditing interception [1671]

$
0
0
Together will all the fabulous features you are introducing I think it could be find room also for a sort of Audit System more business oriented.
We love the new Log & Interceptor hooks but we also need to pull out of the DbContext an easy POCO object based on 3 level of entities like this:
- (S)avedChangset (1 instance for every SaveChanges() call with at least Time, User, Application & Session Info)
- (E)ntities (a collection of the Entities changed within the same "Saved Changset" with at least TableName & PK)
- (A)ttributes (a collection of Attributes changed within the same "Entity", with at least ColumnName, old-data, new-data)
Built with the aim to fill a three tables DB that will be the starting point for dozens of services just like deferred Publisher/Subscriber patterns, logging, tracing, audit and so on....

and we don't love write hundreds of code lines inspecting the DbContext or some other structures, we would prefer to provide some delegates/functions/actions/what-you-prefer at static/constructor/design time to teach DbContext how to create our POCO class structure and, then, at runtime, pull out our well packaged SEA Audit Structur.

Tons of other enhancements could be realized:
like the optional mapping of this new structure with DbContext objects it-self in order to write the Audit Data into DB together with the BusinesData in the same transaction, and so on....
Comments: I was able to implement something that has worked fairly well for us by deriving all entities I want to track from a base ChangeHistory class as shown below and overriding SaveChanges but I'm not happy with the maintenance requirement that I have to manually maintain all the History entities - since they are boiler plate. It would be great if they could just be dynamically generated and made available as DbSets on the DbContext. I should also mention that there are a few issues with delete using this approach also which aren't deal breakers for me, but might bother ORM purists: 1. Remove() has the unfortunate side effect of nulling out FK relationship fields as soon as you call it. I worked around this by just setting the Action to Delete instead of calling Remove(), and then after I have logged it with FK relations intact inside SaveChanges(), set its item.State back to Deleted before calling base.SaveChanges() so that it actually gets deleted. 2. If you want history changes for entities that cascade delete, you obviously have to change your code to manually delete the children rows you want history on before you delete the parent. The ramification of these two points are that instead of doing the standard: context.Onts.Remove(dbont); you have to do something like: dbont.Action = "Deleted"; foreach (var e in dbont.OntEvents) // manually delete any children that cascade delete e.Action = "Deleted"; I would be willing to take a stab at implementing this, but might need some advice on where would be best to hook the dynamic object generation in, and how best to pass it back up so the dynamically generated history entities are available on the DbContext, or if anyone else has a better approach they can effectively convey, I might be willing to help with that as well. I assume it might be best to shoot for EF7 since the code internals may be changing significantly? Also, since different people would probably want different things in their "ChangeHistory" base class, I'm not sure what would be or even if there is a best approach for making something like this totally generic so that people wouldn't have to override SaveChanges at all out of the box. Anyone have thoughts on that? ``` public class ChangeHistory { [NotMapped] // don't want these history related properties cluttering up the Normal tables to set them all to NotMapped public string Action { get; set; } [NotMapped] public int UserID { get; set; } [NotMapped] public DateTime ModifyDate { get; set; } } public class Person : ChangeHistory { [Key] public int Id { get; set; } public string First { get; set; } public string Last { get; set; } } public class PersonHistory // this is the part I wish could be generated as it is boiler plate - these classes are always the same as the class they are tracking, just tack on ModifyDate to the [Key], and adds UserID and Action so you know who did what when. { [Key, Order = 0] public int Id { get; set; } public string First { get; set; } public string Last { get; set; } [Key, Order = 1] public DateTime ModifyDate { get; set; } public int UserID { get; set; } public string Action { get; set; } // Delete, Insert, Update } public class TestContext : DbContext { private void LogChangeToHistoryTable(DbEntityEntry item) { string fullname = item.Entity.GetType().FullName; string entitytype = fullname.StartsWith("System.Data.Entity.DynamicProxies.") ? item.Entity.GetType().BaseType.FullName : fullname; string historytype = string.Format("{0}History", entitytype); var histobj = Activator.CreateInstance(Type.GetType(historytype), null); foreach (var prop in item.Entity.GetType().GetProperties()) { var pi = histobj.GetType().GetProperty(prop.Name); if (pi != null) pi.SetValue(histobj, prop.GetValue(item.Entity, null)); } using (var ctx = new TestContext()) { var sprop = ctx.GetType().GetProperties().First(d => d.GetMethod.ToString().Contains(historytype)); // find the proper dbset and log the change var dbset = sprop.GetValue(ctx, null); // this works but could probably be made more robust MethodInfo method = dbset.GetType().GetMethod("Add"); object result = method.Invoke(dbset, new object[] { histobj }); ctx.SaveChanges(); } } public override int SaveChanges() { // get the items that need to save history and update their modifydate and userid - this saves the user from having to explicitly set these values var historables = ChangeTracker.Entries<ChangeHistory>().Where(h=>h.State != EntityState.Unchanged || h.Entity.Action == "Deleted").ToList(); var deleted = new List<DbEntityEntry<ChangeHistory>>(); foreach (var item in historables) { item.Entity.ModifyDate = DateTime.Now; item.Entity.UserID = GetCurrentUserID(); // this is a hack but it works - DbSet.Remove() has the unfortunate side effect of nulling out all the FK relationship fields as soon as // you call it - so instead of using that, you just set the "Action" property on a historable derived object to "Deleted" and then after // the deletion has been logged, reset item.State to Deleted so the object actually does get deleted from the database if (item.Entity.Action == "Deleted") { LogChangeToHistoryTable(item); item.State = EntityState.Deleted; deleted.Add(item); } else { item.Entity.Action = item.State.ToString(); } } // now - save the changes - this will fill in any identity values, etc. on inserts that we need to be filled in before we can save the history object int retval = 0; try { retval = base.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException e) { foreach (var err in e.EntityValidationErrors) { Console.WriteLine("Validation error, Type = {0}, Object = {1}, Msgs = {2}", err.Entry.Entity.GetType().ToString(), err.Entry.Entity.ToString(), string.Join("\t", from ve in err.ValidationErrors select ve.ErrorMessage)); } } catch (Exception e) { Console.WriteLine(e); } foreach (var item in deleted) historables.Remove(item); // finally, log the history changes to the proper table if they haven't already been logged as deletions above foreach (var item in historables) LogChangeToHistoryTable(item); return retval; } private int GetCurrentUserID() // lookup the current userid - for web apps, Windows Auth is required { int userid = 0; User user; if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "w3wp") { Type type = Type.GetType("System.Web.HttpContext, System.Web, Version=4.0.0.0, PublicKeyToken=b03f5f7f11d50a3a", true, true); PropertyInfo pi = null; if (type != null && (pi = type.GetProperty("Current", (BindingFlags.Public | BindingFlags.Static))) != null) { object httpcontext = pi.GetValue(null,null); if (httpcontext != null) { pi = httpcontext.GetType().GetProperty("User"); if (pi != null) { object httpuser = pi.GetValue(httpcontext, null); if (httpuser != null) { pi = httpuser.GetType().GetProperty("Identity"); if (pi != null) { object httpident = pi.GetValue(httpuser, null); if (httpident != null) { pi = httpident.GetType().GetProperty("Name"); if (pi != null) { string fullname = (string)pi.GetValue(httpident, null); if ((user = Users.FirstOrDefault(u => u.Login == fullname)) != null) userid = user.UserID; } } } } } } } } else // assume CLI or other native non-web app { string fullname = string.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName); if ((user = Users.FirstOrDefault(u => u.Login == fullname)) != null) userid = user.UserID; } return userid; } } ```

Edited Issue: [Perf] Regression introduced by changeset 604533a309d7 [2446]

$
0
0
The introduction of changeset [604533a309d7](https://entityframework.codeplex.com/SourceControl/changeset/604533a309d7e74a38cf9859a3ed2d442ea4d638) regressed model building between 16% and 18% for larger models, as shown by one of our perf tests.

The overall model building time is now to the same levels as EF 6.1.1 since this regression almost exactly matches the improvement made by the fix to #2298. See the attached image for details.

A fix is being worked on.

Commented Issue: [Perf] Regression introduced by changeset 604533a309d7 [2446]

$
0
0
The introduction of changeset [604533a309d7](https://entityframework.codeplex.com/SourceControl/changeset/604533a309d7e74a38cf9859a3ed2d442ea4d638) regressed model building between 16% and 18% for larger models, as shown by one of our perf tests.

The overall model building time is now to the same levels as EF 6.1.1 since this regression almost exactly matches the improvement made by the fix to #2298. See the attached image for details.

A fix is being worked on.
Comments: Resolved with changeset [61de93b8af5a](https://entityframework.codeplex.com/SourceControl/changeset/61de93b8af5a8d622b1f9e26ca7e25e2c78ebb67).

Closed Issue: Concurrency issue in key properties code [2429]

$
0
0
A recent perf improvement involved some metadata caching around key properties. The concurrency test for this just failed on my machine indicating that there is likely a thread-safety issue in this code.

```
Test assembly: C:\ef\test\EntityFramework\UnitTests\bin\Release\EntityFramework.UnitTests.dll
C:\ef\EF.msbuild(93,5): error : System.Data.Entity.Core.Metadata.Edm.EntityTypeBaseTests.KeyProperties_is_thread_safe:
Assert.True() Failure
C:\ef\EF.msbuild(93,5): error : at System.Data.Entity.Core.Metadata.Edm.EntityTypeBaseTests.<>c__DisplayClass7.<KeyProperties_is_thread_safe>b__4() in c:\ef\test\EntityFramework\UnitTests\Core\Metadata\Edm\EntityTypeBaseTests.cs:line 77
C:\ef\EF.msbuild(93,5): error : at System.Threading.Tasks.Task.InnerInvoke()
C:\ef\EF.msbuild(93,5): error : at System.Threading.Tasks.Task.Execute()
```

Comments: Closing, fix verified.

Closed Unassigned: IdentityDbContext issue when using DbMigration and custom connection string [2374]

$
0
0
(Copied from https://aspnetidentity.codeplex.com/workitem/2248)

Using the DbMigrator with a custom connection string and the IdentityDbContext fails. This is most likely due to the behaviour of the default constructor.

```C#
This does not work:
var config = new Configuration();
config.TargetDatabase = new DbConnectionInfo(connectionString, "System.Data.SqlClient");
var migrator = new DbMigrator(config);
```
neither does this
```C#
var config = new Configuration();
config.TargetDatabase = new DbConnectionInfo("MyConnectionName);
var migrator = new DbMigrator(config);
```
The only way i was able to get this to work was to inject the connection string into the application config at runtime. Thus I got this working by doing the following:
```C#
var config = new Configuration();
typeof(ConfigurationElementCollection).GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ConfigurationManager.ConnectionStrings, false);
ConfigurationManager.ConnectionStrings.Remove("MyConnectionName");
ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings("MyConnectionName", connectionString, "System.Data.SqlClient"));
var migrator = new DbMigrator(config);
```
Comments: i was not able to reproduce this and customer (in the parent issue) is not responding, closing

Commented Unassigned: nullablewhere null [2436]

$
0
0
Hi

I have a db bigInt mapped in entity as an Int64.

If I use a previously declared nullable long variable in an entity query I do not get any results if the value of this variable is "null"

An example:
```
long? registrationNumber = null;
objectContext.Persons.Where(p => c.RegNumber == registrationNumber).Count();
```

Creates an SQL Statement with

> where pers_regnumber = NULL

As with other types like Int32 I would have expected this to create a "
> where pers_regnumber is null


As a hotfix I have used this to create a correct SQL
```
long? registrationNumber = null;
objectContext.Persons.Where(p => c.RegNumber == registrationNumber || (registrationNumber == null && c.RegNumber == null)).Count();
```
I am using EF 6.1.0.

Comments: For ObjectContext you can set context.ContextOptions.UseCSharpNullComparisonBehavior = true to get the expected result in this case. The option defaults to false (database null comparison behavior). We changed the default to true for DbContext and if I remember correctly we decided to not change it for ObjectContext because it is considered legacy functionality. Also, I tried the repro with a Nullable<Int32> variable and property, and an int column. It seems to behave the same, as expected. Have you encountered scenarios where the result is not consistent (different SQL generated for Int32 vs Int64)? If yes, could you provide an example of that?

Commented Unassigned: nullablewhere null [2436]

$
0
0
Hi

I have a db bigInt mapped in entity as an Int64.

If I use a previously declared nullable long variable in an entity query I do not get any results if the value of this variable is "null"

An example:
```
long? registrationNumber = null;
objectContext.Persons.Where(p => c.RegNumber == registrationNumber).Count();
```

Creates an SQL Statement with

> where pers_regnumber = NULL

As with other types like Int32 I would have expected this to create a "
> where pers_regnumber is null


As a hotfix I have used this to create a correct SQL
```
long? registrationNumber = null;
objectContext.Persons.Where(p => c.RegNumber == registrationNumber || (registrationNumber == null && c.RegNumber == null)).Count();
```
I am using EF 6.1.0.

Comments: I forgot to mention that the similar option for DbContext (but negated) is available as context.Configuration.UseDatabaseNullSemantics, being false by default.

Edited Unassigned: migrations problem running not startup project in solution [2470]

$
0
0
Hi all,
In the last days/weeks I experienced a strange problem trying to Running migrations in an azure websites.
I have a mobile services Solutions and I added a universal app project,, using vs 2013 update 3, and nuget latest version, but I installed nuteg ctp 1 and uninstalled after a few days.
When I tried to run Add-Migration or Update-Database I have a lot of problems: timeouts, messages that pending changes and so on.
Running with -Verbose switch I seen that was looking for the startup project first and nuget project first, and if I have the Windows 8 as startup project I have a lot of problems.
Switching the mobile service as startup project when I have to run migrations solved the problems.

Edited Unassigned: DatabaseLogger throws System.ArgumentOutOfRangeException [2468]

$
0
0
Can you please make a Thread safe StreamWriter?

System.ArgumentOutOfRangeException
Message Count cannot be less than zero. Parameter name: count
Source mscorlib
TargetSite Void CopyTo(Int32, Char[], Int32, Int32)
StackTrace at System.String.CopyTo(Int32 sourceIndex, Char[] destination, Int32 destinationIndex, Int32 count) at System.IO.StreamWriter.Write(String value) at System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter.Opened(DbConnection connection, DbConnectionInterceptionContext interceptionContext) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.<>c__DisplayClass3`2.<DispatchAsync>b__2(Task t) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass4.<<ExecuteAsync>b__3>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<ExecuteAsyncImplementation>d__9`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.EntityClient.EntityConnection.<OpenAsync>d__8.MoveNext


Env:
EntityFramework version="6.1.1"

<interceptors>
<interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
<parameters>
<parameter value="D:\Logs\LogOutput.txt"/>
</parameters>
</interceptor>
</interceptors>


Commented Unassigned: EF track back the detached entity after 30 minutes or so [2399]

$
0
0
Hi,

I was referred to this site by msdn.

Here is my original post from that site.

[http://social.msdn.microsoft.com/Forums/en-US/a939d0ed-7aec-4955-8aef-1c508ef07b89/multiplicity-constraint-violated-multiplicity-1-or-01?forum=adodotnetentityframework](http://social.msdn.microsoft.com/Forums/en-US/a939d0ed-7aec-4955-8aef-1c508ef07b89/multiplicity-constraint-violated-multiplicity-1-or-01?forum=adodotnetentityframework )



Any idea why EF track back the detached entity after 30 minutes or so?

Thanks
Comments: Hi Luke, This is the error message I got, I hope that would help you. Multiplicity constraint violated. The role 'Procedure' of the relationship 'MSMC.DataModel.BalloonsProcedure' has multiplicity 1 or 0..1. System.InvalidOperationException: Multiplicity constraint violated. The role 'Procedure' of the relationship 'MSMC.DataModel.BalloonsProcedure' has multiplicity 1 or 0..1. at System.Data.Objects.DataClasses.EntityReference`1.VerifyNavigationPropertyForAdd(IEntityWrapper wrapper) at System.Data.Objects.EntityEntry.DetectChangesInRelationshipsOfSingleEntity() at System.Data.Objects.ObjectStateManager.DetectChangesInNavigationProperties(IList`1 entries) at System.Data.Objects.ObjectStateManager.DetectChanges() at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force) at System.Data.Entity.Internal.InternalContext.GetStateEntries(Func`2 predicate) at System.Data.Entity.Internal.InternalContext.GetStateEntries() at System.Data.Entity.Infrastructure.DbChangeTracker.Entries() at System.Data.Entity.DbContext.GetValidationErrors() at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at MSMC.CATH.Interface.CATHEntities.Save() and to support the log of the user when it was first retrieve and when was the last save ACTION ACTIONDATE ACTIONTIME View 20140804 093820 Add 20140804 094508 <<< retrieval time Modify 20140804 112330 <<< saving time. The error was created during this action. see the interval of the last action taken which is 094508 Modify 20140804 112820 Close 20140804 112825 View 20140804 113457 Close 20140804 113543 Here is the association of the object <Association Name="BalloonsProcedure"> <End Type="MSMC.DataModel.Balloon" Role="Balloons" Multiplicity="*" /> <End Type="MSMC.DataModel.Procedure" Role="Procedure" Multiplicity="1" /> <ReferentialConstraint> <Principal Role="Procedure"> <PropertyRef Name="Id" /> </Principal> <Dependent Role="Balloons"> <PropertyRef Name="ProcedureId" /> </Dependent> </ReferentialConstraint> </Association> I load it this way.. _Balloons = New List(Of Balloon) For Each item In _Procedure.Balloons.ToList _Repository.Detach(item) _Balloons.Add(item) Next Prepare for edit ( _BalloonsPerVessel will be listed on grid UI for the user) _BalloonsPerVessel = Balloons in which Balloons is Private ReadOnly Property Balloons() As ICollection(Of Balloon) Get Dim tmpList As IList(Of Balloon) Dim ctr As Int16 tmpList = _Balloons.Where(Function(x) x.Vessel = _Intervention.Vessel And x.Segment = _Intervention.Segment).OrderBy(Function(x) x.SerialNo).ToList() ctr = 0 For Each item In tmpList ctr = ctr + 1 item.SerialNo = ctr Next Return tmpList.ToList End Get End Property And add it back this way For Each item In Balloons.ToList _Balloons.Remove(item) 'clear the balloons belongs to that vessel Next For Each item In BalloonsPerVessel.ToList If Not String.IsNullOrEmpty(item.BalloonName) Then _Balloons.Add(item) End If Next _Procedure.Balloons.ToList().ForEach(Sub(o) _Repository.Remove(o)) _Procedure.Balloons.Clear() _Procedure.Balloons = _Balloons.Where(Function(x) x.IsValid = True).ToList after 30 minutes passed hit the _dbContext.Save() then error comes out.

Reopened Unassigned: EF track back the detached entity after 30 minutes or so [2399]

$
0
0
Hi,

I was referred to this site by msdn.

Here is my original post from that site.

[http://social.msdn.microsoft.com/Forums/en-US/a939d0ed-7aec-4955-8aef-1c508ef07b89/multiplicity-constraint-violated-multiplicity-1-or-01?forum=adodotnetentityframework](http://social.msdn.microsoft.com/Forums/en-US/a939d0ed-7aec-4955-8aef-1c508ef07b89/multiplicity-constraint-violated-multiplicity-1-or-01?forum=adodotnetentityframework )



Any idea why EF track back the detached entity after 30 minutes or so?

Thanks

Edited Unassigned: EF track back the detached entity after 30 minutes or so [2399]

$
0
0
Hi,

I was referred to this site by msdn.

Here is my original post from that site.

[http://social.msdn.microsoft.com/Forums/en-US/a939d0ed-7aec-4955-8aef-1c508ef07b89/multiplicity-constraint-violated-multiplicity-1-or-01?forum=adodotnetentityframework](http://social.msdn.microsoft.com/Forums/en-US/a939d0ed-7aec-4955-8aef-1c508ef07b89/multiplicity-constraint-violated-multiplicity-1-or-01?forum=adodotnetentityframework )



Any idea why EF track back the detached entity after 30 minutes or so?

Thanks

Closed Issue: Migrations :: Enable-Migrations -ContextProjectName Foo throws NRE if Foo is invalid project name [2477]

$
0
0
Command:

Enable-Migrations -ContextProjectName Foo


Output:

Get-Project : Project 'Foo' is not found.
At D:\Projects\Investigate2440\packages\EntityFramework.6.1.2-alpha1-30826\tools\EntityFramework.psm1:950 char:16
+ $project = Get-Project $name
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Foo:String) [Get-Project], ItemNotFoundException
+ FullyQualifiedErrorId : NuGetProjectNotFound,NuGet.PowerShell.Commands.GetProjectCommand

Exception calling "BuildProject" with "3" argument(s): "The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))"
At D:\Projects\Investigate2440\packages\EntityFramework.6.1.2-alpha1-30826\tools\EntityFramework.psm1:977 char:5
+ $DTE.Solution.SolutionBuild.BuildProject($configuration, $project.UniqueName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation

System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetPropertyValue[T](Project project, String propertyName)
at System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade(String configurationTypeName, Boolean useContextWorkingDirectory)
at System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable(String contextTypeName)
at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)

Comments: Closing based on triage decision

Commented Unassigned: TypesMatchByConvention NullReferenceException [2466]

$
0
0
I'm getting a NullReferenceException out of TypesMatchByConvention.

I've built a sample application from the same database that's having trouble and the sample application works fine, so I believe the problems have to do with upgrading from EF 4 to EF 6, but it's really hard to track down a bug from a NullReferenceException :/
Comments: Hi Eric, Are you able to create a small piece of code which would reproduce this issue? This would help us debug the issue further. Thanks

Commented Unassigned: error running Add-Migration [2469]

$
0
0
Hi,
I have a project where every time I try to run Add-Migration I obtain this message:

PM> Add-Migration "tabelle fatture" -Verbose
Using StartUp project 'attivitamobileService'.
Using NuGet project 'attivitamobileService'.
System.InvalidOperationException: Sequence contains no matching element
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<GetStoreAssociationTypePairs>d__6e.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__31`3.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__81`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.FindAssociationTypePairs(ICollection`1 entityTypePairs)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.Design.MigrationScaffolder.Scaffold(String migrationName, Boolean ignoreChanges)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Scaffold(MigrationScaffolder scaffolder)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Sequence contains no matching element

What's wrong?
Comments: Hi Luca, Could you please attach a small project which reproduces this issue? This would help us debug this further. Thanks.
Viewing all 10318 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>