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

Edited Unassigned: Could not load file or assembly EntityFramework Version 5.0.0.0 [2788]

0
0
If I try the EF [Code First Migration sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) with the EF 5.0.0 NuGet package I can create the initial database without problems. At the moment I use the Enable-Migrations command I get the following error message:

PM> Enable-Migrations
Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified."
At C:\Projects\MigrationsDemo\packages\EntityFramework.5.0.0\tools\EntityFramework.psm1:431 char:5
+ $domain.CreateInstanceFrom(
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileNotFoundException

When I update the solution to use an EF 6 NuGet package it works. I noticed this error when I tried to deploy the NuGet Gallery database and I can't upgrade to EF 6 to bypass the error for this project. This error is reported as an [issue](https://github.com/NuGet/NuGetGallery/issues/2592) at the NuGet Gallery GitHub project page by another user and you can also find my research results there. The EF 5 sample works when you use VS 2013 update 4.

Reproduction path:
Start with a VS2013 update 4 and follow the steps reported in the [sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) but use Install-Package EntityFramework -Version 5.0.0 as the command for installing EF 5. Create the initial database and enable migrations. You will see that this works. Remove the Migrations code from your solution and upgrade Visual Studio with update 5. Try to enable migrations again. At that moment you will get the reported error message.

Note: I reported this issue also on [Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/details/1593363/ef-5-0-0-code-first-migrations-doesnt-work-after-upgrading-to-vs2013-5-error-could-not-load-file-or-assembly-entityframework-version-5-0-0-0) for the Visual Studio product group but they closed it with the reason external so I reposted it here.

Edited Issue: We sometimes expose PK values in exception messages [2784]

0
0
Some exceptions contain information about Entity Key value. This may be a security concern, if the key is not surrogate. We should consider not exposing those values via exception messages

Closed Unassigned: Interface type used instead of class when mapping navigation property. [2787]

0
0
EF: 6.1.3

I have a class with a collection that uses an inverse map to define the relationship.
The class also derives from an interface (such as IDictionary).
The problem is that I have mapped the implementation class fluently but when querying against it, it throws an error saying the property does not exist on the class.

> The navigation property 'Localization' is not a declared property on type 'MyLocalizationClass'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.

I believe this is because EF is trying to map instead to the interface type, as removing the IDictionary fixes the issue.

The code is below


```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFTest
{
class Program
{
static void Main(string[] args)
{
var context = new MyContext("Cms");

var locale = context.Locales.First(x => x.Id == 1);
var localizations = locale.Localizations;
}
}
public class MyEntityClass : IDictionary<int, MyLocalizationClass>
{
public int Id { get; set; }
public virtual ICollection<MyLocalizationClass> Localizations { get; set; }

public virtual ICollection<MyLocalizationClass> EntitiesWithLocales { get; set; }

public IEnumerator<KeyValuePair<int, MyLocalizationClass>> GetEnumerator()
{
throw new NotImplementedException();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

public void Add(KeyValuePair<int, MyLocalizationClass> item)
{
throw new NotImplementedException();
}

public void Clear()
{
throw new NotImplementedException();
}

public bool Contains(KeyValuePair<int, MyLocalizationClass> item)
{
throw new NotImplementedException();
}

public void CopyTo(KeyValuePair<int, MyLocalizationClass>[] array, int arrayIndex)
{
throw new NotImplementedException();
}

public bool Remove(KeyValuePair<int, MyLocalizationClass> item)
{
throw new NotImplementedException();
}

public int Count { get; }

public bool IsReadOnly { get; }

public bool ContainsKey(int key)
{
throw new NotImplementedException();
}

public void Add(int key, MyLocalizationClass value)
{
throw new NotImplementedException();
}

public bool Remove(int key)
{
throw new NotImplementedException();
}

public bool TryGetValue(int key, out MyLocalizationClass value)
{
throw new NotImplementedException();
}

public MyLocalizationClass this[int key]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}

public ICollection<int> Keys { get; }

public ICollection<MyLocalizationClass> Values { get; }
}

public class MyLocalizationClass
{
public int Id { get; set; }
public virtual MyEntityClass Localization { get; set; }
public virtual MyEntityClass Entity { get; set; }
}

public class MyContext : DbContext
{
public MyContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}

public DbSet<MyEntityClass> Locales { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntityClass>().ToTable("MyEntityClass");
modelBuilder.Entity<MyLocalizationClass>().ToTable("MyLocalizationClass");
modelBuilder.Entity<MyEntityClass>()
.HasMany(x => x.EntitiesWithLocales)
.WithRequired(x => x.Entity)
.Map(x => x.MapKey("EntityId"));
modelBuilder.Entity<MyEntityClass>().Ignore(x => x.Values);
modelBuilder.Entity<MyLocalizationClass>().HasRequired(x => x.Localization).WithMany().Map(x => x.MapKey("LocaleId"));
base.OnModelCreating(modelBuilder);
}
}
}

```
Comments: Having an entity class implement ICollection (or something that implements ICollection, such as Dictionary) is not supported. We do have an issue tracking it (http://entityframework.codeplex.com/workitem/664) but it's not something we are planning to address in the immediate future.

Closed Unassigned: Explicitly name default constraints similar to how it is done for PK and FK. [2786]

0
0
Reason: otherwise they are named implicitly by server, differently in each db instance, which generates false differences when comparing schemas by Schema Compare.
Comments: This is already fixed in EF7. We aren't planning to back port this to EF6, but we would consider a community contribution with the change.

Commented Unassigned: Breaking Change: Query crashes when compiled with VS2015 RTM (Roslyn compiler) [2785]

0
0
The following query crashes when compiled with VS2015 RTM, but works when compiled with the old compiler in VS2013:

```
public async Task<List<ProductRelation>> FailingQuery(SampleEnum queryOption)
{
using (var context = new SampleContext())
{

int[] ids = await Task.FromResult(new[] { 1, 2, 3, 4 });
return await (from order in context.Set<Order>()
where ids.Contains(order.OrderId)
&& queryOption == SampleEnum.Value1
from pr in context.Set<ProductRelation>()
select pr).ToListAsync();
}
}
```

(Not that the query has been simplified for demonstration purposes, it obviously makes no sense in this shape but I have reduced it as much as possible).

```
Exception:

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Data.Entity.DbSet`1[RoslynEfTest.UnitTest1+ProductRelation] Set[ProductRelation]()' method, and this method cannot be translated into a store expression.
```

I have attached a sample unit-test project which illustrates the error.
Comments: Hey, What version of EF are you using? We did fix a similar issue in 6.1.3, but we're not sure if this is the same thing. ~Rowan

Closed Unassigned: database schema & connection string [2782]

0
0
Hi there,

I have a single project that contains multiple entity models (.edmx) files which in turn are compiled into EF6 data models

I have discovered that file name creation doesn't take into account the Schema specified in the settings on the model designer (.tt).

As a result when I have the same table name in two different databases, which in turn are referenced by two different entity models (.edmx), the compiler crashes out and always deletes one of the .vb files.

As a work around I have added the following code to the .tt template that builds the class files

fileManager.StartNewFile("<schemaname>." & entity.Name & ".vb")

fileManager.StartNewFile("<schemaname>." & complex.Name & ".vb")

fileManager.StartNewFile("<schemaname>." & enumType.Name & ".vb")

The other problem I discovered was that, I use the connection dynamically, each of my systems understands when it is in DEV, UAT or Production and as such changes the connection string accordingly. (no margin for human error)

Add the following code after the first constructor function, within the context.tt

Public Sub New(constr as string)
MyBase.New(constr)
<#
If Not loader.IsLazyLoadingEnabled(container) Then
#>
MyBase.Configuration.LazyLoadingEnabled = False
<#
End If



For Each entitySet As EntitySet In container.BaseEntitySets.OfType(Of EntitySet)()
''' Note: the DbSet members are defined below such that the getter and
''' setter always have the same accessibility as the DbSet definition
If Not Accessibility.ForReadOnlyProperty(entitySet) = "Public"
#>
<#=codeStringGenerator.DbSetInitializer(entitySet)#>
<#
End If
Next
#>
End Sub

Comments: This is a less common scenario, so we are optimized for the more common case. There are two options here: * Change the CustomToolNamespace (property on the T4 template files) to generate the classes for each model in a separate namespace. * Move the models to separate sub-folders, which in turn will give you different namespaces.

Closed Unassigned: No AddRange and RemoveRange methods in IDbSet interface in Entity 6. [2781]

0
0
In Entity Framework 6 new methods AddRange and RemoveRange have been introduced to System.Data.Entity.DbSet class. But they don't exist in System.Data.Entity.IDbSet interface (where Add and Remove methods are defined).

Is it a bug or intentional due some reason?
Comments: This is by design. The interface approach wasn't a good one for DbSet because adding members breaks any existing applications that implement the interface. Given we want to be able to add members to DbSet, we swapped to a base class approach where DbSet is a base class that you can directly mock or inherit. Here are some links that show how to use DbSet rather than IDbSet: * https://msdn.microsoft.com/en-us/data/dn314429 * https://msdn.microsoft.com/en-us/data/dn314431

Closed Unassigned: Getting the column name (SSpace) from a CLR property name is not possible [2779]

0
0
I can see from the following example how to get the table name of an OSpace type:

https://lowrymedia.com/2014/06/10/ef6-1-mapping-between-types-tables-including-derived-types/

But how do I go about getting the SSpace column name from an OSpace property name (i.e. CLR type property)?

By browsing the MetadataProperties from the corresponding CSpace property, I can see there is a "Configuration" entry containing the column name if changed using the Fluid API or ColumnAttribute, but the value of the entry is an internal class on EF's part.

I am then inclined to say that it is not possible to get column name, taking into account the Fluid APi, at this point, without using reflection on EF's internal class.
Comments: Hey, Here is some code that shows how to do this (ugly I know)... it's nicer in EF7 :) ~Rowan ``` using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Core.Mapping; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Infrastructure; using System.Linq; namespace MappingDemo { class Program { static void Main(string[] args) { using (var db = new BlogContext()) { Console.WriteLine("Blog.BlogId maps to: {0}", GetColumnName(typeof(Blog), nameof(Blog.BlogId), db)); Console.WriteLine("Post.Body maps to: {0}", GetColumnName(typeof(Post), nameof(Post.Body), db)); } } public static string GetColumnName(Type type, string propertyName, DbContext context) { var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace; // Get the part of the model that contains info about the actual CLR types var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace)); // Get the entity type from the model that maps to the CLR type var entityType = metadata .GetItems<EntityType>(DataSpace.OSpace) .Single(e => objectItemCollection.GetClrType(e) == type); // Get the entity set that uses this entity type var entitySet = metadata .GetItems<EntityContainer>(DataSpace.CSpace) .Single() .EntitySets .Single(s => s.ElementType.Name == entityType.Name); // Find the mapping between conceptual and storage model for this entity set var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace) .Single() .EntitySetMappings .Single(s => s.EntitySet == entitySet); // Find the storage entity set (table) that the entity is mapped var tableEntitySet = mapping .EntityTypeMappings.Single() .Fragments.Single() .StoreEntitySet; // Return the table name from the storage entity set var tableName = tableEntitySet.MetadataProperties["Table"].Value ?? tableEntitySet.Name; // Find the storage property (column) that the property is mapped var columnName = mapping .EntityTypeMappings.Single() .Fragments.Single() .PropertyMappings .OfType<ScalarPropertyMapping>() .Single(m => m.Property.Name == propertyName) .Column .Name; return tableName + "." + columnName; } } public class BlogContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .ToTable("t_blog"); modelBuilder.Entity<Blog>() .Property(b => b.BlogId) .HasColumnName("blog_id"); modelBuilder.Entity<Post>() .ToTable("t_post"); modelBuilder.Entity<Post>() .Property(b => b.Body) .HasColumnName("post_body"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Body { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } } ```

Commented Unassigned: Breaking Change: Query crashes when compiled with VS2015 RTM (Roslyn compiler) [2785]

0
0
The following query crashes when compiled with VS2015 RTM, but works when compiled with the old compiler in VS2013:

```
public async Task<List<ProductRelation>> FailingQuery(SampleEnum queryOption)
{
using (var context = new SampleContext())
{

int[] ids = await Task.FromResult(new[] { 1, 2, 3, 4 });
return await (from order in context.Set<Order>()
where ids.Contains(order.OrderId)
&& queryOption == SampleEnum.Value1
from pr in context.Set<ProductRelation>()
select pr).ToListAsync();
}
}
```

(Not that the query has been simplified for demonstration purposes, it obviously makes no sense in this shape but I have reduced it as much as possible).

```
Exception:

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Data.Entity.DbSet`1[RoslynEfTest.UnitTest1+ProductRelation] Set[ProductRelation]()' method, and this method cannot be translated into a store expression.
```

I have attached a sample unit-test project which illustrates the error.
Comments: Hi, I am on 6.1.3 I have attached a repro unit test project.

Created Unassigned: Concurrency checking does not work when Entity Framework is used with Web API 2 Odata Controllers [2789]

0
0
When saving an Entity Framework (6.1.3) entity with a Timestamp column (concurrency mode set to "Fixed"), Entity Framework uses the original value obtained when the entity was first loaded for the purposes of concurrency checking. This works fine with connected entities but does not work for disconnected entities in Web API projects.

For example, when creating a new Web API 2 Odata Controller the generated code for the PUT and PATCH methods follow this structure:

```
// PUT: odata/Users(5)
public IHttpActionResult Put([FromODataUri] int key, Delta<User> patch)
{
Validate(patch.GetEntity());

if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

User user = db.Users.Find(key);
if (user == null)
{
return NotFound();
}

patch.Put(user);

try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!UserExists(key))
{
return NotFound();
}
else
{
throw;
}
}

return Updated(user);
}
```

Amongst other data, the "patch" parameter contains the Timestamp value when the data was previously loaded from the controller using one of the "Get" methods.

The PUT and PATCH methods load the relevant entity from the database, apply the changes and then saves the entity back to the database. During this process, the current value of the Timestamp column is set to the value from the "patch" parameter; the old value.

However when Entity Framework saves the changes, the value of the Timestamp column obtained during "User user = db.Users.Find(key);" is used for the concurrency check.

Because of this behaviour concurrency checking does not work. Only changes that occur in the very small time window between "User user = db.Users.Find(key);" and "db.SaveChanges();" are detected.

Changing Entity Framework to use the current value of the Timestamp column will correct this behaviour.

To resolve this, I've created and applied a custom interface to all entities requiring this fix (IConcurrencyCheckedEntity) and have overridden SaveChanges as below:

```
public override int SaveChanges()
{
foreach (DbEntityEntry<IConcurrencyCheckedEntity> entry in ChangeTracker.Entries<IConcurrencyCheckedEntity>().Where(u => u.State == EntityState.Modified))
entry.Property("Timestamp").OriginalValue = entry.Property("Timestamp").CurrentValue;

return base.SaveChanges();
}
```

With this in place, Entity Framework uses the current value of the Timestamp for concurrency checking.
This has resolved the issue for me and seems to have no negative impact.

However I'd like to understand whether this is by design and why?

Edited Unassigned: Concurrency checking does not work when Entity Framework is used with Web API 2 Odata Controllers [2789]

0
0
When saving an Entity Framework (6.1.3) entity with a Timestamp column (concurrency mode set to "Fixed"), Entity Framework uses the original value obtained when the entity was first loaded for the purposes of concurrency checking. This works fine with connected entities but does not work for disconnected entities in Web API projects.

(See Stack Overflow: http://stackoverflow.com/questions/20952336/how-do-you-use-optimistic-concurrency-with-webapi-odata-controller)

For example, when creating a new Web API 2 Odata Controller the generated code for the PUT and PATCH methods follow this structure:

```
// PUT: odata/Users(5)
public IHttpActionResult Put([FromODataUri] int key, Delta<User> patch)
{
Validate(patch.GetEntity());

if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

User user = db.Users.Find(key);
if (user == null)
{
return NotFound();
}

patch.Put(user);

try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!UserExists(key))
{
return NotFound();
}
else
{
throw;
}
}

return Updated(user);
}
```

Amongst other data, the "patch" parameter contains the Timestamp value when the data was previously loaded from the controller using one of the "Get" methods.

The PUT and PATCH methods load the relevant entity from the database, apply the changes and then saves the entity back to the database. During this process, the current value of the Timestamp column is set to the value from the "patch" parameter; the old value.

However when Entity Framework saves the changes, the value of the Timestamp column obtained during "User user = db.Users.Find(key);" is used for the concurrency check.

Because of this behaviour concurrency checking does not work. Only changes that occur in the very small time window between "User user = db.Users.Find(key);" and "db.SaveChanges();" are detected.

Changing Entity Framework to use the current value of the Timestamp column will correct this behaviour.

To resolve this, I've created and applied a custom interface to all entities requiring this fix (IConcurrencyCheckedEntity) and have overridden SaveChanges as below:

```
public override int SaveChanges()
{
foreach (DbEntityEntry<IConcurrencyCheckedEntity> entry in ChangeTracker.Entries<IConcurrencyCheckedEntity>().Where(u => u.State == EntityState.Modified))
entry.Property("Timestamp").OriginalValue = entry.Property("Timestamp").CurrentValue;

return base.SaveChanges();
}
```

With this in place, Entity Framework uses the current value of the Timestamp for concurrency checking.
This has resolved the issue for me and seems to have no negative impact.

However I'd like to understand whether this is by design and why?

Edited Issue: Breaking Change: Query crashes when compiled with VS2015 RTM (Roslyn compiler) [2785]

0
0
The following query crashes when compiled with VS2015 RTM, but works when compiled with the old compiler in VS2013:

```
public async Task<List<ProductRelation>> FailingQuery(SampleEnum queryOption)
{
using (var context = new SampleContext())
{

int[] ids = await Task.FromResult(new[] { 1, 2, 3, 4 });
return await (from order in context.Set<Order>()
where ids.Contains(order.OrderId)
&& queryOption == SampleEnum.Value1
from pr in context.Set<ProductRelation>()
select pr).ToListAsync();
}
}
```

(Not that the query has been simplified for demonstration purposes, it obviously makes no sense in this shape but I have reduced it as much as possible).

```
Exception:

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Data.Entity.DbSet`1[RoslynEfTest.UnitTest1+ProductRelation] Set[ProductRelation]()' method, and this method cannot be translated into a store expression.
```

I have attached a sample unit-test project which illustrates the error.

Reviewed: EF 6.1.3 (七月 31, 2015)

0
0
Rated 5 Stars (out of 5) - this is good

Created Unassigned: Entities materialized by SqlQuery don't display lazy loading [2790]

0
0
Compare these two snippets (in Linqpad, connected to a DbContext):

```
var prd1 = this.Database.SqlQuery<Product>("Select * From Product").First();
Entry(prd1).State.Dump(); // Detached
prd1.Categories.Dump(); // (0 items)
```
And
```
var prd2 = Products.AsNoTracking().ToArray().First();
Entry(prd2).State.Dump(); // Detached
prd2.Categories.Dump(); // (2 items)
```
In both snippets, `prd` and `prd2` are proxy objects. Still, in the first snippet lazy loading is not triggered, whereas in the second, it is. This also shows in the executed queries.

When in the first snippet the `prd1` object is attached to the context as `Unchanged` lazy loading _does_ occur.

I think this is inconsistent behavior. If a proxy is materialized by any EF process, I think it should be capable of lazy loading.

Edited Unassigned: Entities materialized by SqlQuery don't display lazy loading [2790]

0
0
Compare these two snippets (in Linqpad, connected to a DbContext):

```
var prd1 = this.Database.SqlQuery<Product>("Select * From Product").First();
Entry(prd1).State.Dump(); // Detached
prd1.Categories.Dump(); // (0 items)
```
And
```
var prd2 = Products.AsNoTracking().ToArray().First();
Entry(prd2).State.Dump(); // Detached
prd2.Categories.Dump(); // (2 items)
```
In both snippets, `prd` and `prd2` are proxy objects. Still, in the first snippet lazy loading is not triggered, whereas in the second, it is. This also shows in the executed queries.

When in the first snippet the `prd1` object is attached to the context as `Unchanged` lazy loading _does_ occur.

I think this is inconsistent behavior. If a proxy is materialized by any EF process, I think it should be capable of lazy loading.

(EF 6.1.3, .Net 4.0).

Edited Unassigned: Entities materialized by SqlQuery don't display lazy loading [2790]

0
0
Compare these two snippets (in Linqpad, connected to a DbContext):

```
var prd1 = this.Database.SqlQuery<Product>("Select * From Product").First();
Entry(prd1).State.Dump(); // Detached
prd1.Categories.Dump(); // (0 items)
```
And
```
var prd2 = Products.AsNoTracking().ToArray().First();
Entry(prd2).State.Dump(); // Detached
prd2.Categories.Dump(); // (2 items)
```
In both snippets, `prd` and `prd2` are proxy objects. Still, in the first snippet lazy loading is not triggered, whereas in the second, it is. This also shows in the executed queries.

When in the first snippet the `prd1` object is attached to the context as `Unchanged` lazy loading _does_ occur.

I think this is inconsistent behavior. If a proxy is materialized by any EF process, I think it should be capable of lazy loading.

Probably related: the entities from `SqlQuery` don't respond to relationship fixup either. If they have `Categories` collections in a 1:n association, these won't be populated if the belonging categories are loaded separately by a `Load` statement.

(EF 6.1.3, .Net 4.0).

New Comment on "Getting and Building EF Runtime"

0
0
public virtual IList<NamedDbProviderService> DbProviderServices { get { return _providerServices.Value; } } An unhandled exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll Additional information: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

New Comment on "Nightly Builds"

0
0
When Using Manually nightly builds Giving Error public virtual IList<NamedDbProviderService> DbProviderServices { get { return _providerServices.Value; } } An unhandled exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll Additional information: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Commented Unassigned: Could not load file or assembly EntityFramework Version 5.0.0.0 [2788]

0
0
If I try the EF [Code First Migration sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) with the EF 5.0.0 NuGet package I can create the initial database without problems. At the moment I use the Enable-Migrations command I get the following error message:

PM> Enable-Migrations
Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified."
At C:\Projects\MigrationsDemo\packages\EntityFramework.5.0.0\tools\EntityFramework.psm1:431 char:5
+ $domain.CreateInstanceFrom(
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileNotFoundException

When I update the solution to use an EF 6 NuGet package it works. I noticed this error when I tried to deploy the NuGet Gallery database and I can't upgrade to EF 6 to bypass the error for this project. This error is reported as an [issue](https://github.com/NuGet/NuGetGallery/issues/2592) at the NuGet Gallery GitHub project page by another user and you can also find my research results there. The EF 5 sample works when you use VS 2013 update 4.

Reproduction path:
Start with a VS2013 update 4 and follow the steps reported in the [sample](https://msdn.microsoft.com/en-us/data/jj591621.aspx) but use Install-Package EntityFramework -Version 5.0.0 as the command for installing EF 5. Create the initial database and enable migrations. You will see that this works. Remove the Migrations code from your solution and upgrade Visual Studio with update 5. Try to enable migrations again. At that moment you will get the reported error message.

Note: I reported this issue also on [Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/details/1593363/ef-5-0-0-code-first-migrations-doesnt-work-after-upgrading-to-vs2013-5-error-could-not-load-file-or-assembly-entityframework-version-5-0-0-0) for the Visual Studio product group but they closed it with the reason external so I reposted it here.
Comments: Seeing the same issue. Seems related to EF5 not supporting the newer NuGet PoSh console.

Created Unassigned: Sequence contains more than one element - 2 joins between entities using stored procedure mappings [2791]

0
0
Hi,

I get the error "Sequence contains more than one element" when joining the same 2 entities twice and using MapToStoredProcedures(). See the code below. If you remove the MapToStoredProcedure() calls in the configuration classes, then the code runs.

```
public class TableOne
{
public int TableOneId { get; set; }
public virtual TableTwo TableTwo_1 { get; set; }
public virtual TableTwo TableTwo_2 { get; set; }
}

public class TableTwo
{
public int TableTwoId { get; set; }
}

public class TableOneMap : EntityTypeConfiguration<TableOne>
{
public TableOneMap()
{
// Primary Key
HasKey(t => t.TableOneId);

// Relationships
HasRequired(t => t.TableTwo_1)
.WithMany()
.Map(d => d.MapKey("TableTwoId_1"))
.WillCascadeOnDelete(false);

HasRequired(t => t.TableTwo_2)
.WithMany()
.Map(d => d.MapKey("TableTwoId_2"))
.WillCascadeOnDelete(false);

MapToStoredProcedures();
}
}

public class TableTwoMap : EntityTypeConfiguration<TableTwo>
{
public TableTwoMap()
{
// Primary Key
HasKey(t => t.TableTwoId);

MapToStoredProcedures();
}
}

public class EFTestContextSeedIntialiser : DropCreateDatabaseAlways<EFTestContext>
{
protected override void Seed(EFTestContext context)
{
var table2_1 = new TableTwo();
var table2_2 = new TableTwo();

var table1 = new TableOne()
{
TableTwo_1 = table2_1,
TableTwo_2 = table2_2
};

context.Set<TableOne>().Add(table1);
context.SaveChanges();
}
}

public class EFTestContext : DbContext
{
public EFTestContext()
: base("Name=EFTestContext")
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TableOneMap());
modelBuilder.Configurations.Add(new TableTwoMap());
}
}


class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new EFTestContextSeedIntialiser());
var context = new EFTestContext();
context.Database.Initialize(true);

System.Console.WriteLine("First Join: " + context.Set<TableOne>().First().TableTwo_1.TableTwoId);
System.Console.WriteLine("Second Join: " + context.Set<TableOne>().First().TableTwo_2.TableTwoId);

System.Console.ReadLine();
}
}
```

A first chance exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
System.Transactions Critical: 0 : http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/UnhandledUnhandled exceptionConsole.vshost.exeSystem.InvalidOperationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Sequence contains more than one element at System.Linq.Enumerable.SingleOrDefaultTSource
at System.Data.Entity.Migrations.Infrastructure.ModificationCommandTreeGenerator.ChangeRelationshipStates(DbContext context, EntityType entityType, Object entity, EntityState state)
at System.Data.Entity.Migrations.Infrastructure.ModificationCommandTreeGenerator.&lt;Generate&gt;d__14.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at System.Linq.Enumerable.&amp;lt;CastIterator&amp;gt;d__b11.MoveNext()
at System.Linq.Buffer1..ctor(IEnumerable1 source)
at System.Linq.Enumerable.ToArrayTSource
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.GenerateFunctionBodyTCommandTree
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.GenerateUpdateFunctionBody(EntityTypeModificationFunctionMapping modificationFunctionMapping, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator) at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.&amp;lt;BuildCreateProcedureOperations&amp;gt;d__15f.MoveNext() at System.Linq.Enumerable.&amp;lt;SelectManyIterator&amp;gt;d__313.MoveNext()
at System.Linq.Enumerable.&lt;ConcatIterator&gt;d__711.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion) at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.&lt;&gt;c__DisplayClassc.&lt;Update&gt;b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update()
at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func3 createMigrator, ObjectContext objectContext) at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState) at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) at System.Data.Entity.DropCreateDatabaseAlways1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.&lt;&gt;c__DisplayClassf1.&amp;lt;CreateInitializationAction&amp;gt;b__e() at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() at System.Data.Entity.Database.Initialize(Boolean force) at Console.Program.Main(String[] args) in c:\Users\ajohnc\Documents\Visual Studio 2013\Projects\EFPowerToolsTest\Console\Program.cs:line 91 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()</StackTrace><ExceptionString>System.InvalidOperationException: Sequence contains more than one element at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source)
at System.Data.Entity.Migrations.Infrastructure.ModificationCommandTreeGenerator.ChangeRelationshipStates(DbContext context, EntityType entityType, Object entity, EntityState state)
at System.Data.Entity.Migrations.Infrastructure.ModificationCommandTreeGenerator.&lt;Generate&gt;d__14.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at System.Linq.Enumerable.&amp;lt;CastIterator&amp;gt;d__b11.MoveNext()
at System.Linq.Buffer1..ctor(IEnumerable1 source)
at System.Linq.Enumerable.ToArrayTSource
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.GenerateFunctionBodyTCommandTree
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.GenerateUpdateFunctionBody(EntityTypeModificationFunctionMapping modificationFunctionMapping, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator) at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.&amp;lt;BuildCreateProcedureOperations&amp;gt;d__15f.MoveNext() at System.Linq.Enumerable.&amp;lt;SelectManyIterator&amp;gt;d__313.MoveNext()
at System.Linq.Enumerable.&lt;ConcatIterator&gt;d__711.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion) at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Upgra
Viewing all 10318 articles
Browse latest View live




Latest Images