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

Commented Feature: Code First: Error when class with same name as entity class but in a different namespace [911]

$
0
0
This is a metabug since this issue (which is tracked by 483) is now fixed when using Code First. The fix for this when using Database First or Model First will be post-EF6.

A canonical example of this bug is having a Product entity that is included in your model and then a separate Product DTO that is defined in a different namespace. In EF5 and earlier we would throw because EF couldn't work out which Product class to use... but in the case of Code First we know which one to use because you define you model in terms of your CLR classes.

See item 483 for more details: http://entityframework.codeplex.com/workitem/483

Comments: I'm getting this error: The type 'NamespaceA.Client' and the type 'ExternalNamespace.Dto.Client' both have the same simple name of 'Client' and so cannot be used in the same model. All types in a given model must have unique simple names. Use 'NotMappedAttribute' or call Ignore in the Code First fluent API to explicitly exclude a property or type from the model. I don't think this should happen.

Commented Issue: Unable to cast Anonymous Type from 'System.Linq.IQueryable' to 'System.Data.Entity.Core.Objects.ObjectQuery' [1751]

$
0
0
After posting a [question](http://stackoverflow.com/questions/19455105/ef5-query-doesnt-work-with-ef6) at StackOverflow about my issue, some user suggest me to post the error here.

The following query was working well with EF5 but gives me error with EF6. I use DbContext and CodeFirst.

#Error raised with EF6:

> Unable to cast the type 'System.Linq.IQueryable`1[[<>f__AnonymousType5`4[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Wms.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=85d69d39f5becc93]]' to type 'System.Data.Entity.Core.Objects.ObjectQuery`1[[<>f__AnonymousType5`4[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Wms.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=85d69d39f5becc93]]'. LINQ to Entities only supports casting EDM primitive or enumeration types.


#Query (simplified):

var unitsPerPosition = context.Positions.Include(p => p.Unit).Select(x => new { Unit = x.Unit, Position = x });

var orders = (
from order in context.Orders.Include(x => x.SourceLocation);
join unitPosition in unitsPerPosition on order.UnitId equals unitPosition.Unit.UnitId
group new { order, unitPosition } by new { LocationId = order.SourceLocationId, Level = unitPosition.Position.Level } into groupOrders
where groupOrders.Key.LocationId != null
select new {
LocationId = groupOrders.Key.LocationId.Value,
Level = groupOrders.Key.Level,
LoadingOrders = groupOrders.Count(),
UnloadingOrders = -1 }
);

IList<LocationChannels> searchResult = (from s in context.Locations
.Include(s => s.Positions)
.Include(s => s.Positions.Select(sp => sp.Unit))

let channels = from p in s.Positions
where p.LocationId == s.LocationId
group p by new { p.LocationId, p.Column, p.Level } into channelsGroup

join order in orders on new { channelsGroup.Key.LocationId, channelsGroup.Key.Level }
equals new { order.LocationId, order.Level } into ordersGroup
from o in ordersGroup.DefaultIfEmpty()

select new Channel
{
LocationId = channelsGroup.Key.LocationId,
Column = channelsGroup.Key.Column,
Level = channelsGroup.Key.Level
}

select new LocationChannels
{
Location = s,
Channels = channels,
})
.Where(predicate).ToList();

The issue appears to be on the left join with the anonymous type loaded in variable 'orders'. I also tried to add a ToList() to the 'orders' query but then the error change to:

> Unable to create a constant value of type 'Anonymous type'. Only primitive types or enumeration types are supported in this context.

Can someone gives me an hint on how to fix it?
Comments: @ajcvickers - The change looks pretty simple. We have been hit by this, and rather than take a nightly build that has who-knows-what in it, I'm inclined to cherry-pick your commit on top of 6.0.1 and build it myself. Any reason you can think of this would be a bad idea? Thanks

Commented Unassigned: Actually use MigrationOperation.AnonymousArguments to do...things... [1840]

$
0
0
In a custom migration I was attempting to use the form of `DbMigration.Sql()` that takes an anonymous object to pass parameters for a paramterized query. [The documentation implies that this is the way it's meant to work but provides no full examples](http://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigration.sql(v=vs.113).aspx), and no matter what I tried I could not get it to work.

[See the confusion that ensued on Stackoverflow](http://stackoverflow.com/questions/20034612/how-to-pass-parameters-to-dbmigration-sql-method/20035646?noredirect=1#20035646)

So I dug into the source code, and track the argument back to `MigrationOperation.AnonymousArguments` which seems to be used ... only in some unit tests.

So what's going on? Is this argument used at all? If not can it, and the misleading for of the `Sql(... ... ...)` method be removed?
Comments: @RoMiller can we then at least get the documentation of the `Sql()` method updated to make that clear? You can see how ``` Additional arguments that may be processed by providers. Use anonymous type syntax to specify arguments e.g. 'new { SampleArgument = "MyValue" }'. ``` sounds like the intention is for it to be used as a parameterized query. From asking around, I know at least one other developer that got tripped up on the exact same thing because of the docs and spent several hours trying to figure it out.

New Post: Updating EF4 Model from Database in VS2013 doesn't update

$
0
0
I have upgraded a VS2010 project using EF4 to VS2013 and everything seemed to be working fine, however I've added a new stored procedure to the database and I can't get the model to update. I've selected 'Update Model From Database' then chosen the new sproc from the treeview and clicked 'finish' but the model is not updated and I cannot see the sproc to link to a function.

I am able to add tables to my database and these are imported as entities, but no stored procedures.

Any ideas?

New Post: Updating EF4 Model from Database in VS2013 doesn't update

$
0
0
Ok, so i've solved it:

I needed to uncheck the "Import Selected Stored Procedures and Functions into the Entity Model".

Commented Issue: NuGet Package install fails with F# projects [891]

$
0
0
Reported via blog - http://blogs.msdn.com/b/adonet/archive/2012/12/10/ef6-alpha-2-available-on-nuget.aspx?CommentPosted=true#10394085

I got the following exception, doesn't look like a major issue but want to update. I am writing my code in F# if that has anything to do with it.

PM> Install-Package EntityFramework -Pre

You are downloading EntityFramework from Microsoft, the license agreement to which is available at go.microsoft.com/fwlink. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.

Successfully installed 'EntityFramework 6.0.0-alpha2'.

Successfully added 'EntityFramework 6.0.0-alpha2' to DALEntities.

Exception calling "CreateInstanceFrom" with "8" argument(s): "Type 'Microsoft.VisualStudio.FSharp.ProjectSystem.Automation.OAProject' in assembly

'FSharp.ProjectSystem.Base, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable."

At C:\Users\shashi\SkyDrive\Code\CommonDAL\packages\EntityFramework.6.0.0-alpha2\tools\install.ps1:10 char:5

+ $appDomain.CreateInstanceFrom(

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : SerializationException

Type 'get-help EntityFramework' to see all available Entity Framework commands.

PM>

Comments: Voted. Broken with v6.0.1. Even a suggested workaround would be nice.

New Post: Exclude columns in the Select

$
0
0
I'm using Entity Framework 6.0.2

In all my tables have the following columns to the log:
user_create
date_create
user_modify
date_modify

These columns are updated by the method override SaveChanges ();

My question is the following:
Exists as to ignore these columns when loading work a SELECT operation?
The only way I found is to carry through Linq specifying which columns I want, but it can not use the object of the entity, requiring a class of DTO.

Thanks for help

Updated Wiki: Contributing

$
0
0

Ways to Contribute

If you would like to contribute, consider these options:

  • Submit a bug report (for an guide on submitting good bug reports, readPainless Bug Tracking).
  • Verify fixes for bugs.
  • Submit a code fix for a bug.
  • Submit a feature request.
  • Help answer questions in the discussions list.
  • Submit a unit test.
  • Tell others about the project.
  • Tell the developers how much you appreciate the product!

Contributing Code

Make sure you can build the code. Familiarize yourself with theproject guidelines and ourcoding conventions. You might also read these two good blogs posts on contributing code:Open Source Contribution Etiquette by Miguel de Icaza andDon’t “Push” Your Pull Requests by Ilya Grigorik.

Before submitting a feature or substantial code contribution please discuss it with the team and ensure it follows the product roadmap. Note that all code submissions will be rigorously reviewed and tested by the Entity Framework Team, and only those that meet an extremely high bar for both quality and design/roadmap appropriateness will be merged into the source.

 

You will need to submit a Contributor License Agreement form before submitting your pull request. This needs to only be done once for any Microsoft Open Technologies OSS project. Download the Contributor License Agreement (CLA). Please fill in, sign, scan and email it tomsopentech-cla@microsoft.com.

Then follow these steps:

  1. Decide what feature or bug fix you plan to take on and start a discussion with the title of the bug so we know someone is already working on it. e.g. "I'm going to fix issue 59: Something's Broken." If you're just starting out, pick something small to fix such as:
    • Add a missing unit test.
    • Fix an FxCop issue.
    • Fix a defect in the issue list (do a search for “UpForGrabs” or just find one with the “Proposed” status). Try something small first and work your way up to larger issues.
  2. Create a fork of the project.
  3. Clone the fork you created in the previous step to your machine.
  4. Make the relevant changes in your local clone (potentially adding a unit test if this is a bug fix).
  5. Please only contribute code which you wrote or have the rights to contribute. If you do need to add 3rd party code pleasediscuss it with us first.
  6. Run build.cmd (if changing runtime code) or BuildEFTools.cmd (if changing tooling code) from the command line and make sure that there are 0 errors.
  7. Commit your changes in your local clone. You may end up repeating steps 4-6 multiple times as you work. When you are finished and ready to have us accept your change, go to step 8.
  8. Pull from origin and merge your changes with the latest from origin (fix any merge conflicts you might have).
  9. If multiple local commits have been made, squash them into a single commit using git rebase -i.
  10. Push your changes up to your fork.
  11. Go to the source control tab and send a pull request. Make sure the summary contains relevant bug numbers and a good description of your changes.
  12. If you need to revise your code, then do so locally and update the review. Repeat until we approve the review.
  13. Wait for your review to be approved. We'll try to get to it as soon as possible. Once the review is approved, someone from the team will push your changes to the main source repository. Then you can delete your fork.

New Post: Testing with async queries doesn't work

$
0
0
@ajcvickers

Thanks!

Still couldn't get it working but wow, that article misses a lot of things

New Post: using system; at code-migrations

$
0
0
Just a small request, is it possible to remove the using "System" from the code-migrations template?

The using is not used in the migration and will generate a re-sharper error :)

Commented Issue: Incorrect compilation of chains of ternary operators [1857]

$
0
0
When compiling LINQ query to SQL, the multiple nested ternary expressions of the form `x => x == 1 ? 2 : x == 3 ? 4 : x == 5 ? 6 : 7` correctly produce a `CASE` statement like `CASE WHEN x=1 THEN 2 WHEN x=3 THEN 4 WHEN x=5 THEN 6 ELSE 7 END`.

However, if the result happens to be large enough, the generator produces several nested `CASE` statements instead, like this: `CASE WHEN x=1 THEN 2 ELSE CASE WHEN x=3 THEN 4 ELSE CASE WHEN x=5 THEN 6 ELSE 7 END END END`. Which by itself should be fine, if not for the fact that SQL Server only supports such nested CASEs to the maximum nesting depth of ten.

In our particular scenario, every condition is a `.Contains()` call instead of simple equality, and the sets on which these calls are made are relatively large - on the scale of thousands of items. The number of ternary operators themselves, however, is not that large - up to a hundred, often significantly less.
The limitation that we have discovered seems to be that the total number of items in all sets is no more than *around* 25K. I say "around", because it is actually not the same from occurrence to occurrence and seems to fluctuate depending on the number of ternary operators.

Attached it a small self-contained test (uses xUnit), which presently fails at 26K items. If you change the number `26000` in the fourth line of the method to `24000`, the test passes.

P.S. Just to answer the obvious question of "_why do you need to do this kind of crazy thing in the first place_". What we *really* need are table-valued parameters, but in their absence we're forced to replace the table with a giant CASE statement.

P.P.S. We use EF 5. Have not tried it on the new version.
Comments: Assigning to Emil for 6.1 - we should investigate if case flattening should be taking care of this.

New Post: SQL Server Compact 3.5 provider for EF6

Closed Unassigned: Entity Framework not able to get results when 3rd party provider returns column numbers in the result set [1809]

$
0
0
Entity Framework not able to get results when 3rd party provider returns column numbers in the result set
Current behavior : Since the DB2 stored procedure returns multiple results with column numbers( Not Names), it is not getting identified with entity framework and hence Identifier is empty or null is coming as in the document that’s shared with you earlier.
Expected behavior : To see the result set even when the stored procedure call returns results with column numbers.


Comments: __EF Team Triage:__ The requirement for column names is fundamental to how EF is implemented. Unfortunately, given the amount of work required to remove this constraint, it is not something that we are planning to do.

Closed Unassigned: Add attrribute manager to apply to code generated items [1856]

$
0
0
Add attrribute manager to apply to code generated items.

This should allow us to build a list of default attrributes to apply to Properties and classes.

e.g. DataAnnotations / Own Attributes / Attriubtes to support 3rd party UI Frameworks etc...

Please indicate if more info is required
Comments: __EF Team Triage:__ This isn't something that our team is going to add to the designer. The 'buddy class' approach mentioned in the StackOverflow thread is the best approach to take. You can also modify the T4 code generation templates to add in attributes if needed. Whilst our team isn't going to implement this, we would consider accepting a pull request if you wanted to contribute the feature.

Closed Feature: ModelNamespaceConvention: Make ctor public [1854]

$
0
0
We should make this public so that customers have a way to override the default EDM conceptual namespace.
Comments: __EF Team Triage:__ This request was raised by another team at Microsoft. We believe there is a better way to achieve what they want, so we are not planning to implement this.

Edited Feature: UpForGrabs: Mark pure methods with PureAttribute [1846]

$
0
0
Please consider making pure methods of ObjectQuery, DbQuery and their generic counterparts with PureAttribute. First of all it concerns all variants of Include(), since developers make oftentimes the same mistake by losing a modified query copy returned by the the method. A PureAttribute would help smart IDE Tolls like R# to issue a warning in that case.

Commented Feature: UpForGrabs: Mark pure methods with PureAttribute [1846]

$
0
0
Please consider making pure methods of ObjectQuery, DbQuery and their generic counterparts with PureAttribute. First of all it concerns all variants of Include(), since developers make oftentimes the same mistake by losing a modified query copy returned by the the method. A PureAttribute would help smart IDE Tolls like R# to issue a warning in that case.
Comments: __EF Team Triage:__ We aren't planning to implement this in the 6.x set of releases but we would accept a pull request for the change. One thing to keep in mind is that some methods (such as ToList) are not pure. Marking them as pure would cause a warning if you just called them without using the result - but in EF they do have side effects and can legitimately be called without using the result.

Closed Unassigned: Use Fully Qualified Names [1844]

$
0
0
Version: EF6

Issue:
When generating the DBContext class, the code fails to compile if the table name coincides with a System name, for example "Environment".

The fix would be to modify the tt template to always use the fully qualified name when generating the context class.
An added suggestion would be to default to using fully qualified type names in ALL generated code.

![Image](https://www.codeplex.com/Download/AttachmentDownload.ashx?ProjectName=entityframework&WorkItemId=1844&FileAttachmentId=759489)
Comments: __EF Team Triage:__ We make an effort to keep the generated code as simple as possible. Given that it's not common to have your entity type names conflict with a type in the set of namespaces that are imported, we are not planning to make this change. If you need this, the T4 templates can easily be modified to use the fully qualified name.

Closed Issue: Code First: TPC with two abstract base classes fails [981]

$
0
0
The following code fails to build a model because there are two abstract base classes before the first concrete class. Removing BillingDetailBase causes the model to be successfully built.

```
public class MyContext : DbContext
{
public DbSet<User> Users { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BankAccount>().Map(m =>
{
m.ToTable("BankAccounts");
m.MapInheritedProperties();
});

modelBuilder.Entity<CreditCard>().Map(m =>
{
m.ToTable("CreditCards");
m.MapInheritedProperties();
});
}
}

public abstract class BillingDetailBase
{
public Int32 Id { get; set; }
}

public abstract class BillingDetail : BillingDetailBase
{
public string Owner { get; set; }
}

public class User
{
public int UserId { get; set; }
public virtual BillingDetailBase BillingDetail { get; set; }
}

public class BankAccount : BillingDetail
{
public string BankName { get; set; }
public string Swift { get; set; }
}

public class CreditCard : BillingDetail
{
public int CardType { get; set; }
public string ExpiryMonth { get; set; }
public string ExpiryYear { get; set; }
}
```

The error that gets generated is:

```
System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:

\tBillingDetailBase: : The referenced EntitySet 'BillingDetailBase' for End 'BillingDetailBase' could not be found in the containing EntityContainer.

at System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate()
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.get_CodeFirstModel()
at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at Microsoft.DbContextPackage.Handlers.ViewContextHandler.ViewContext(MenuCommand menuCommand, Object context, Type systemContextType)
```
Comments: Verified fixed. The original issue and the slightly different version that Maurycy had, are both fixed.

Commented Unassigned: Model validation should fail, when HasRequired is set for optional foreign key. [1845]

$
0
0
Suppose you have these models:

```
public class A
{
public int Id { get; set; }
// other properties here
}

public class B
{
public int Id { get; set; }
// other properties here
}

public class C
{
public int Id { get; set; }
public int? AId { get; set; }
public A A { get; set; }
public int? BId { get; set; }
public B B { get; set; }
// other properties here
}

```
and `C` is configured this way:

```
class CConfig : EntityTypeConfiguration<C>
{
public CConfig()
{
// other properties and keys

HasRequired(_ => _.A)
.WithMany()
.HasForeignKey(_ => _.AId);
HasRequired(_ => _.B)
.WithMany()
.HasForeignKey(_ => _.BId);
}
}

```
Note, that navigation properties are configured with errors: as they're optional, `HasOptional` instead of `HasRequired` should be used.

Later, query like this:

```
context
.CEntities
.Where(c => c.A == null || c.B == null);
```

will produce SQL like this:

```
SELECT
-- here are C fields
FROM C_Table AS [Extent1]
WHERE ((1 = 0) OR (1 = 0))

```
which will return empty result set every time.

This behavior isn't obvious. Instead of generating invalid SQL, model validation should fail, when `HasRequired` is set for optional foreign key.
Comments: __EF Team Triage:__ This is actually by design. Although the CLR property is nullable, we do allow you to mark the relationship as required. This can be useful if you want to temporarily assign null to the foreign key property as part of your business logic - but then fix it up before saving. It's also useful when you don't have control of the entity class definitions. We agree the generated SQL is a little strange - but it should still be very fast to execute.
Viewing all 10318 articles
Browse latest View live


Latest Images