我想做一个基本的Address
班,许多不同的其他班可以有(公司可以有一个帐单地址和送货地址,每个员工有一个家庭地址等)。我正在做这个模型 - 首先在EF4中,我认为我可以做一个单向导航,但这是行不通的。这里是我的:实体框架4单向导航/关系。我究竟做错了什么?
edmx模型。请注意,我创建了一个1-1关系,然后删除了导航属性Address
,以便只有Companies
和Employees
引用Address
,但该地址未引用其所有者。
生成的SQL看起来是正确的,因为它创建所有3个表,然后强制执行公司 - >地址和员工 - >地址的关系,并执行不执行的地址 - >公司或地址 - >员工关系。
-- Creating table 'Addresses'
CREATE TABLE [Addresses] (
[Id] int IDENTITY(1,1) NOT NULL,
[Street] nvarchar(4000) NOT NULL,
[City] nvarchar(4000) NOT NULL,
[State] nvarchar(4000) NOT NULL,
[Zip] nvarchar(4000) NOT NULL
);
GO
-- Creating table 'Companies'
CREATE TABLE [Companies] (
[Id] int IDENTITY(1,1) NOT NULL,
[Name] nvarchar(4000) NOT NULL,
[Address_Id] int NOT NULL
);
GO
-- Creating table 'Employees'
CREATE TABLE [Employees] (
[Id] int IDENTITY(1,1) NOT NULL,
[Name] nvarchar(4000) NOT NULL,
[Address_Id] int NOT NULL
);
GO
-- Creating foreign key on [Address_Id] in table 'Companies'
ALTER TABLE [Companies]
ADD CONSTRAINT [FK_CompanyAddress]
FOREIGN KEY ([Address_Id])
REFERENCES [Addresses]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- Creating foreign key on [Address_Id] in table 'Employees'
ALTER TABLE [Employees]
ADD CONSTRAINT [FK_EmployeeAddress]
FOREIGN KEY ([Address_Id])
REFERENCES [Addresses]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
现在我要插入一个Company
及其Address
...
[TestMethod]
public void TestMethod1()
{
var context = new Model1Container();
context.AddToCompanies(new Company
{
Name = "TestCompany",
Address = new Address
{
Street = "TestAddress"
}
});
context.SaveChanges();
}
测试失败上SaveChanges()
出现错误:
System.Data.UpdateException: Entities in 'Model1Container.Addresses' participate in the 'EmployeeAddress' relationship. 0 related 'Employee' were found. 1 'Employee' is expected.
所以它看起来像EF试图在公司的地址上执行不可通航的地址 - >员工关系...
我该如何做这项工作?这似乎是这种关系是相当普遍的做法...感谢您的任何帮助!
感谢您的回复。在EF中对此进行建模的“正确”方式是什么?在C#类中,我基本上想要:'class Address {}''class Employee {public Address EmployeeAddress; }'和'class Company {public Address CompanyAddress; }在EF中是否真的没有办法模拟这种关系? – CodingWithSpike
如果不能重复使用地址,将地址存储在单独的表中有什么意义?它看起来更像是你需要一个复杂的类型。在实体的情况下,你必须开始改变关系1:0..1 –
我认为复杂类型确实是我真正想要的。这正确地分离了C#中的“Address”类型的数据。在数据库中,它将所有字段存储在同一个表中,但我想这并不重要。我想我只是将面向对象的逻辑应用于数据库布局,这是错误的。谢谢您的帮助! – CodingWithSpike