In my project we are using the EF Code First (v.6.0.0.0) and the MS SQL Server 2012.
I've updated to the Entity Framework to the 6th version. The strange thing that at some point after the update I started getting duplicated items while filtering records by the primary key.
First of all I started to get the 'Sequence contains more than one element' exception in the following code
var cateringService = context.CateringServices
.SingleOrDefault(x => x.Id == query.CateringServiceId)
I've checked the database and the parameter - the Id
is a primary key, it is marked as unique, and the parameter was valid. As the Id
was set as primary key in the mapping:
this.HasKey(x => x.Id);
I've replaces the call with the FirstOrDefault
and code worked well.
I've tried to retrieve all the items that are mathing the predicate using the following code:
var cateringServices = context.CateringServices
.Where(x => x.Id == query.CateringServiceId)
.ToList();
It seemed that I'm getting the 13 instances of the 'CateringService' entity referencing the same row. Please look at the screenshots attached:
As well I've started to get the A relationship multiplicity constraint violation occurred: An EntityReference can have no more than one related object, but the query returned more than one related object.
exception while accessing the CateringService entities via entity reference. We are using the lazy approach and lazy loading is enabled.
When trying to access the 'CateringService' using the Include("CateringService")
everythings works well, but we can not just replace all the SingleOrDefault
calls and remove all the lazy loading usages from the project at this point.
Please advise.
UPDATE
Sorry for being not quite clear.
There is a single record in the database that matches the condition.
The Id
column is set as the Primary Key so it is unique.
UPDATE 2
Below is the code from the migration generated by EF based on fluent mappings.
CreateTable(
"dbo.CateringServices",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 200),
CreatedDate = c.DateTime(nullable: false),
CultureString = c.String(maxLength: 10),
AddressId = c.Int(),
CateringServiceGroupId = c.Int(),
ContactInformationId = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Addresses", t => t.AddressId, cascadeDelete: true)
.ForeignKey("dbo.CateringServiceGroups", t => t.CateringServiceGroupId)
.ForeignKey("dbo.ContactInformation", t => t.ContactInformationId, cascadeDelete: true)
.Index(t => t.AddressId)
.Index(t => t.CateringServiceGroupId)
.Index(t => t.ContactInformationId);