在我的项目中,我们使用的是EF代码第一次(v.6.0.0.0)和MS SQL Server 2012的实体框架6.0代码第一 - 按主键
我在过滤时在一个简单的查询得到复制项目已经更新到实体框架第6版。 奇怪的是,在更新后的某个时候,我开始获取重复的项目,同时通过主键过滤记录。
首先,我开始得到“序列包含多个元素”在下面的代码
var cateringService = context.CateringServices
.SingleOrDefault(x => x.Id == query.CateringServiceId)
我检查了数据库和参数例外 - 该Id
是主键 ,它被标记为唯一,并且该参数是有效的。作为Id
设定为在映射主键:
this.HasKey(x => x.Id);
我已经取代了电话与FirstOrDefault
和代码运行良好。 我试着检索所有正在使用下面的代码mathing谓词的项目:
var cateringServices = context.CateringServices
.Where(x => x.Id == query.CateringServiceId)
.ToList();
看来,我得到了“CateringService”实体的13个实例引用同一行。请看附截图:
除了我已经开始得到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.
例外,同时通过实体引用访问CateringService实体。我们正在使用懒惰的方法,并启用延迟加载。
当试图使用Include("CateringService")
访问'CateringService'时,所有的操作都很好,但我们不能只替换所有的SingleOrDefault
调用,并且在此时删除项目中的所有惰性加载用法。
请指教。
UPDATE
对不起,我是不太清楚。 数据库中有一条记录与条件匹配。 Id
列设置为主键,因此它是唯一的。
UPDATE 2
下面是基于流利映射由EF生成迁移代码。
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);
你的代码中'query'的定义是什么? ('x.Id == query.CateringServiceId') –
它是一个非常简单的类的实例 - 只有一个属性'public Int32 CateringServiceId {get;组; }' – danyloid
但我试过使用硬编码值,例如'x => x.Id == 1'。或数据库中的任何其他现有ID。仍然得到相同的结果。 – danyloid