我一直在编写一个非常大的项目,并且遇到了 EF4 和连接器表操作的问题。
假设我们有以下 SQL 表定义:
CREATE TABLE [dbo].[SQLEntity](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Field1] [nvarchar](128) NOT NULL,
[Field2] [nvarchar] (256),
[DateAdded] [datetime] NOT NULL,
CONSTRAINT [PK_SQLEntity] PRIMARY KEY CLUSTERED (
[Id] ASC
) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Util_LookupValues](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Description] [nvarchar](64) NOT NULL,
CONSTRAINT [PK_Util_LookupValues] PRIMARY KEY CLUSTERED (
[Id] ASC
)WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Xref_EntityValues](
[SQLEntityId] [bigint] NOT NULL,
[LookupId] [int] NOT NULL,
CONSTRAINT [PK_Xref_PositionBenefits] PRIMARY KEY CLUSTERED (
[SQLEntityId] ASC,
[LookupId] ASC
)WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Xref_EntityValues] WITH CHECK ADD CONSTRAINT [FK_Xref_EntityValues_Entity] FOREIGN KEY([SQLEntityId])
REFERENCES [dbo].[SQLEntity] ([Id])
GO
ALTER TABLE [dbo].[Xref_EntityValues] CHECK CONSTRAINT [FK_Xref_EntityValues_Entity]
GO
ALTER TABLE [dbo].[Xref_EntityValues] WITH CHECK ADD CONSTRAINT [FK_Xref_EntityValues_Util_LookupValues] FOREIGN KEY([LookupId])
REFERENCES [dbo].[Util_LookupValues] ([Id])
GO
ALTER TABLE [dbo].[Xref_EntityValues] CHECK CONSTRAINT [FK_Xref_EntityValues_Util_LookupValues]
GO
一旦基于这些表创建了域模型,您最终会得到两个实体:SqlEntity 和 Util_LookupValues。
此时,Util_LookupValues 是一个表,其值仅用于查找!Xref_EntityValues 是一个连接器表,它将实体对象与查找值联系在一起,允许我们在两者之间建立一对一的关系,保留查找表的“查找”功能。
Util_LookupValues 内容
Id Description
--- ------------
1 Person
2 Car
如果没有向域模型添加任何更改(让我们将此问题称为 DataEntities),则将 SQLEntity 与 PK 为 1 和 2 的 Util_LookupValues 对象绑定如下:
IEnumerable<Util_LookupValues> lookupValues = DataEntities.Util_LookupValues.Where( lv => lv.Id == 1 || lv.Id == 2);
SQLEntity entity = new SQLEntity();
entity.Field1 = "some field";
entity.Field2 = "another field";
entity.DateAdded = DateTime.Now;
foreach(Util_LookupValues val in lookupValues)
{
entity.Util_LookupValues.Add(val);
}
DataEntities.SQLEntities.Add(entity);
DataEntities.SaveChanges();
但问题是,该代码不仅向 Xref_EntityValues 添加值,还使用新键向 Util_LookupValues 添加了 1 和 2 的副本!生成的数据库如下:
SQL Entity:
Id Field1 Field2 DateAdded
-- ------- ------ ----------
1 some field another field 04/04/2012
Xref_EntityValues:
SQLEntityId LookupId
----------- ---------
1 3
1 4
and Util_LookupValues:
Id Description
--- ------------
1 Person
2 Car
3 Person
4 Car
如何使 Util_LookupValues 仅具有 2 条原始记录而 Xref_EntityValues 具有正确的外键?
Xref_EntityValues:
SQLEntityId LookupId
----------- ---------
1 1
1 2
Util_LookupValues:
Id Description
--- ------------
1 Person
2 Car