Error: EntityType name has no key defined. Define the key for this EntityType.

Possibly save 1 hour of your time: You may encounter this error if you didn’t define the Key attribute (like the primary key).

[Key]
public string UniqueCode { get; set; }

 

 

 

 

Advertisements

System.InvalidOperationException : Unable to determine composite primary key ordering for type Name. Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys

Possibly save 1 hour of your time: You may encounter this error if you have multiple keys but didn’t define the column order.


[Table("your_table_name")]
public partial class YourEntityName
{
[Key]
[Column(Order = 1)]
public int Year { get; set; }

[Key]
[Column(Order = 2)]
[StringLength(3)]
public string CountryCode { get; set; }

public double Value { get; set; }
}

 

Setup Entity Framework v6.x

Possibly save 4 hours of your time: This is a brief introduction of setting your project to use Entity Framework v6.

  • Install Entity Framework
  • Create DbContext derived class
  • Create Entity model
  • Add connectionString to configuration
  • Write functional test

Install Entity Framework

In Visual Studio, make sure your project solution is open. Now go to Tools >> NuGet Package Manager >> Manage NuGet Packages for solution…

Select Browse >> then search for EntityFramework. The latest version is v6.2.0 at this time of writing for .NET Framework 4.5.2.

Then check the checkbox for the projects in your solution you want to install. Then click Install.

Once installed, you should see the following references:

  • EntityFramework
  • EntityFramework.SqlServer
  • System.ComponentModel.DataAnnotations

Create DbContext derived class

Next, you need to create a class that inherits from System.Data.Entity.DbContext.

Then create a constructor with the name of the connection string used in the configuration later.

Next you will need to create a property which is a System.Data.Entity.DbSet<entity model> that represents your database table. DbSet is like a collection of the entity models.


public class SomeNameContext : DbContext
 {
  public SomeNameContext() : base("name=SomeNameContext")
  {
  }

  public virtual DbSet<YourEntityName> YourEntitiesName { get; set; }
 }

Create Entity model

You will then create the partial class for the entity model. The model will need a Table attribute with the name of the table as argument.

When you create the properties, you can specify other property attributes such as:

  • Key – represents primary key
  • Column(Order = 1) – must specify column order if multiple keys exist
  • StringLength(30) – limit to 30 characters

[Table("your_db_table_name")]
 public partial class YourEntityName
 {
  [Key]
  [Column(Order = 1)]
  public int Year { get; set; }

  [Key]
  [Column(Order = 2)]
  [StringLength(3)]
  public string CountryCode { get; set; }

  public double Value { get; set; }
 }

Add connectionString to configuration

In the project web or application configuration (web.config or app.config) file add the connectionStrings section if it is not already there and add an element for your connection string.

<connectionStrings>
<add name="SomeNameContext" connectionString="data source=localhost;initial catalog=YourDatabaseName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<connectionStrings/>

Write functional test

Using NUnit.Framework, we can test with the following:


[TestFixture]
public class AlbertaExportValueTests
{
[Test]
public void Test()
{
using (var context = new ExportToolContext())
{
var albertaExports = context.AlbertaExportValues.ToList();
Assert.That(albertaExports.Count, Is.EqualTo(260702));
}
}
}

Reference:

https://msdn.microsoft.com/en-us/data/jj591583

Programming Entity Framework: Code First: Creating and Configuring Data Models from Your Classes

Entity Framework transaction handling via SaveChanges

Possibly save 1 hour of your time: A common question that was asked is how to handle transaction within your application.
Fortunately, if you are using Entity Framework, it already does the heavy lifting work for you.
When you modify your entities in the application, it will track model and property changes behind the scene. And then when you call the following line of code, it will persists all updates to the database and resets change tracking in the object context.
objectContext.SaveChanges();

 

ObjectContext is the object that represents the database connection and its entities.

There may be situations when you may call this more than once in a request to create multiple transactions. I cannot think of a reason right now, but just remember that this acts like a commit transaction as each SaveChanges call will create a new transaction.

However, there are also cases where you may have more than one context to deal with. In that case you may pull data from one database and save them to another database. In this case, you may want to put both contexts’ SaveChanges calls in a TransactionScope to protect this as one atomic transaction.

References:

ObjectContext.SaveChanges Method ()

https://msdn.microsoft.com/en-us/library/bb336792(v=vs.110).aspx

LINQ and Entity Framework Errors

Possibly save 4 hours of your time: When working with LINQ and Entity Framework 6, you may encounter the following errors.

  1. Only parameterless constructors and initializers are supported in LINQ to Entities.
  2. The ‘Distinct’ operation cannot be applied to the collection ResultType of the specified argument. Parameter name: argument
    This happens on Union operation of two entities with different schemas
  3. An error occurred while preparing the command definition. See the inner exception for details.
    This happens on Union operation of Concat operation on two entities with different schemas
  4. System.InvalidOperationException : The specified cast from a materialized ‘System.Int32’ type to the ‘System.String’ type is not valid.
    This happens on Union or Concat operation on two entities with different schemas.

First one is obvious, you must have parameterless constructor when selecting new object transformation.

from i in dbcontext.TableName

select new EntityObjectName() { ID = i.ID }

Second and Third one is similar. When you select new object with properties that are in array form, you may get these errors. One idea would be to simply change this to IEnumerable or IList.

Fourth, this one took me awhile to figure out. It basically happens when the property being transformed came from two different tables and have different data types on the database backend. A simple fix is to check for null and turn into empty string on both the union/concat select. This seems to fix the issue.

from i in dbcontext.TableName

select new EntityObjectName() { Value = i.Value ?? “” }

UNION or CONCAT

from j in dbcontext.TableName2

select new EntityObjectName() { Value = j.Value2 ?? “” }

Programming Entity Framework: Code First: Creating and Configuring Data Models from Your Classes