Entity Framework Archives - Digital Tool Factory blog Entity Framework Archives - Digital Tool Factory blog

The Digital Tool Factory Blog

The peculiar problem when your entity framework query returns the same row for every record

This one had me confused for a long time, several hours in fact.  There were over 8,000 rows in the table, and the for some reason the query was returning the same row 8,000 times.  After much rending of garments and gnashing of teeth, I discovered that the table in question (in a sql server 2000 database (not created by me)) had no primary key defined.

So – I copy the data into a new table, create a key with the commands

alter table TableInQuestion
add NewIDColumn int identity(1,1)

Delete the empty key field (that was what threw me, there was a column named “Id”, which was not actually and ID column.) rename “NewIDColumn” to “Id”, then point EF to the new table with the data attribute (on the object)

[Table(“TableInQuestion”)]

and everything works like a charm

 


22
Sep 17


Written By Steve French

 

Connecting Entity Framework to Sql Server 2000

A lesson learned – when trying to map Entity Framework to Sql Server 2000  (if you must) – make sure that there are no nullable dates – if so, work around them.  I just spent hours looking into that.


25
Jul 17


Written By Steve French

 

Linq projection with the extension method syntax

I’ve looked this up an embarrassing number of times – here is how you do linq projection with the extension method syntax

List<TypeClassification> typeClassifications = ctx.Classes.Select(e => new TypeClassification() {Name = e.Name, TypeClassificationID = e.ClassificationID}).ToList();

Hopefully I shall remember.  I’m not sure why I can’t remember the exact syntax.


18
Apr 14


Written By Steve French

 

Five things should should know about the new asp.net identity membership system

I’m trying my first asp.net mvc 5 project, which more or less forces you to use the new asp.net identity framework for membership. It’s in the using Microsoft.AspNet.Identity namespace.

While a vast improvement over the original asp.net membership – I do not see any massive benefit over the MVC 4 Simple Membership system.  Here are 5 things you need to know about the asp.net identity system before you upgrade

  1. The ID column is stored as a guid, and not an int – One of my favorite things about the simple membership system was being able to use int columns for ID – no more of that
  2. In the default project, all of the membership tables will be stored in Local DB, even if you change the connection string in the web.config
  3. MVC introduces a peculiar (to me at least) way of creating the Database tables for membership in the LocalDB – in the IdentityModel.cs file in the Models folder, you will see the following bit of code

    public class ApplicationDbContext : IdentityDbContextWithCustomUser
    {
    }

    this will create the following tables in the Local DB

    • ASPNetUsers
    • ASPNeRoles
    • ASPNeTokens
    • ASPNetUserClaims
    • ASPNetUserLogins
    • ASPNetUserManagements
    • ASPNetUserRoles
    • ASPNetUserSecrets

    if you are running a separate database you will find it quite confusing to get the membership and the other data in the same context (the error message are rather opaque.  To fix the matter, add in the following code in your regular data context class and comment out the ApplicationDbContext : IdentityDbContextWithCustomUser in IdentityModel.cs

    public DbSet ApplicationUsers { get; set; }
    public DbSet Roles { get; set; }
    public DbSet Tokens { get; set; }
    public DbSet UserClaims { get; set; }
    public DbSet UserLogins { get; set; }
    public DbSet UserManagements { get; set; }
    public DbSet UserRoles { get; set; }
    public DbSet UserSecrets { get; set; }

    and everything will both be in the same database and the same data context.

  4. The quick and easy way of getting the User ID (comparable to WebSecurity.CurrentUserID is User.Identity.GetUserID() – that will return the guid of the user.
  5. It is pleasantly integrated with entity framework code first, and will probably be a positive feature over time.

05
Oct 13


Written By Steve French

 

How to fix the “error 2025: XML Schema validation failed for mapping schema.” error

The Problem

You’ve been upgrading and downgrading Entity Framework, and just when everything seems to be working, you get an error of

Schema specified is not valid. Errors:
<File Unknown>(0,0) : error 2025: XML Schema validation failed for mapping schema. Schema Error Information : The ‘http://schemas.microsoft.com/ado/2012/10/edm/migrations:IsSystem’ attribute is not declared..
<File Unknown>(0,0) : error 2025: XML Schema validation failed for mapping schema. Schema Error Information : The ‘http://schemas.microsoft.com/ado/2012/10/edm/migrations:IsSystem’ attribute is not declared..
<File Unknown>(0,0) : error 2025: XML Schema validation failed for mapping schema. Schema Error Information : The ‘http://schemas.microsoft.com/ado/2012/10/edm/migrations:IsSystem’ attribute is not declared..
<File Unknown>(0,0) : error 2025: XML Schema validation failed for mapping schema. Schema Error Information : The ‘http://schemas.microsoft.com/ado/2012/10/edm/migrations:IsSystem’ attribute is not declared..
<File Unknown>(0,0) : error 2025: XML Schema validation failed for mapping schema. Schema Error Information : The ‘http://schemas.microsoft.com/ado/2012/10/edm/migrations:IsSystem’ attribute is not declared..
<File Unknown>(0,0) : error 2025: XML Schema validation failed for mapping schema. Schema Error Information : The ‘http://schemas.microsoft.com/ado/2012/10/edm/migrations:IsSystem’ attribute is not declared..
<File Unknown>(0,0) : error 2025: XML Schema validation failed for mapping schema. Schema Error Information : The ‘http://schemas.microsoft.com/ado/2012/10/edm/migrations:IsSystem’ attribute is not declared.

The Cause

The data migrations have gotten out of sync

The Solution

The solution (use at your own risk)

  1. Delete the migrations folder and
  2. Drop the _MigrationHistory table in the database
  3. Run Enable-migrations -Force in the package manager console
  4. Add a migration
  5. Check the migration file that is created – it should have a listing of your entire database – delete the table creation and dropping code
  6. run update-database -verbose

You should be back in business!


04
Jun 13


Written By Steve French

 

How to fix problems with entity framework decimal precision

The Problem

You are attempting to change a database column of type decimal from a precision of two decimal place to one decimal place via data annotations, and there does not seem to be a good way to do it.

The Cause

There isn’t a good way to do it.

The Solution

However, there is at least one non-elegant way to do it – in your OnModelCreating code in your data context, enter in the following piece of code

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity().Property(xx=>xx.Handicap).HasPrecision(12, 1);
base.OnModelCreating(modelBuilder);

}
The “HasPrecision” part is the key – the second parameter is the number of decimal places to use


12
Dec 12


Written By Steve French

 

How to fix problems with ReSharper LINQ Intellisense

The Problem

Resharper’s Intellisense, while generally awesome, does not find navigation properties in Linq statements

The Cause:

No Idea

The Solution

Switch back to Visual Studio 2012’s Intellisense, then go to Resharper > Options > Environment > General and make sure that the “Store Caches in the System Temp Folder

Close and Reopen Visual Studio 2012 and everything should be working well.


18
Oct 12


Written By Steve French

 

How to programatically set the sql server database used by entity framework

The Problem:

'Entity Framework' photo (c) 2009, SondreB - license: http://creativecommons.org/licenses/by/2.0/For one reason or another you need to set the database used by entity framework programatically.  The more common way of doing such a thing is to set the database in your web.config class, but for whatever reason you need to set it in actual C# code.

The Cause:

There is no cause really, it is merely the way that entity framework and sql server work together.

The Solution:

The answer lies in setting the constructor properly.

Example Code Using Entity Framework and Data Context

using System.Data.Entity;

namespace MyDBServerExperiments.Models
{
public class DTFContext : DbContext
{
public DTFContext() : base(“Data Source=MyDBServer.DBServer.com;Initial Catalog=MyEntityFrameworkDB;Persist Security Info=True;user id=MyUsername; Password=MyPassword;”) { }

public DbSet<User> Users { get; set; }
public DbSet<BusinessObjects> BusinessObjects { get; set; }
public DbSet<Property> Properties { get; set; }

}

}

The above would be your data context file that uses the DBContext file  in your models folder, just fyi (that is the common place for Entity Framework models in the standard  Visual Studio 2010 web solution structure).

Note, everything happens in the constructor.  This give you many interesting opportunities to programatically swap out Sql Server database names and users, compared to the web.config option, which tends to be far more static.  It allows far more extensive use of business objects and


24
Apr 12


Written By Steve French

 

How to fix yet another You must set this property to a non-null value of type ‘Double’ problem with Entity Framework

The Problem

You are coding happily away in Visual Studio 2010, working on your asp.net project, using the entity framework and sql server and you get and you get the following error

The ‘Amount’ property on ‘SomeTable’ could not be set to a ‘Decimal’ value. You must set this property to a non-null value of type ‘Double’.

What you say?  Why do I have to set it to non-nullable? It looks something like

public double? Amount { get; set; }

The Cause

The root problem is in your database schema  – something in how that table is set up is not gibing correctly with entity framework.

The Solution

Just set the property to a non-nullable decimal type, for example

public decimal Amount { get; set; }

It’s not a perfect solution, but Entity Framework does not like all sql server data types, and I have yet to find an explanation as to why or a list of things to avoid.  If anyone does know please leave a link in the comments.  This is a persistent problem for me when working with ourside databases, and I’m sure I’m not the only this happens to.  Your input would be quite helpful here Microsoft.  It would be a nice improvement in the next version of Entity Framework.


13
Mar 12


Written By Steve French

 

How to Fix Missing records in Linq to Entities

The Problem

You are attempting to use Linq to Entities in the standard way, your linq model does not seem to have any records attached.  You have missing records in Linq to Entities.

You look in the database, and the proper record is there.  You do a

context.MyEntry.Count().ToString()

and it tells you there is one record there, but still when you attempt to actually retrieve a record, for example like

context.MyEntry.First().FirstName

you get a white screen.  What gives?

The Cause

It turns out the offending code looks like this

namespace MyProject.Models
{
	public class MyEntry
	{
		[Key]
		public int MyEntryId { get; set; }
                public string EmailAddress { get; set; }
                public string LastName { get; set; }
                public string FirstName;
	}
}

The Solution

Did you notice what was missing?  You don’t have the needed

{ get; set; }

after FirstName, so Linq To Entities will not retrieve the record for the database.  It’s always hard to see something missing, it took me about 20 minutes and lots of checking the wrong places to see the omission with this problem.


14
Feb 12


Written By Steve French

 




Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.