[英]Entity Framework inherited one to zero to one relationship configuration with fluent API
I can't find an answer by searching through SO questions and by Googling around. 我无法通过搜索SO问题和谷歌搜索来找到答案。
I have a very simple structure: 我有一个非常简单的结构:
public class Employee
{
property int Id { get; set; }
property int Name { get; set; }
}
public class Developer : Employee
{
property string Level { get; set; }
}
and I have two tables for this domain model: 对于该域模型,我有两个表:
create table Employees
(
Id int not null primary key identity(1, 1),
Name nvarchar(100) not null
)
create table Developers
(
Id int not null primary key,
Level nvarchar(100)
)
alter table Developers
add constraint FK_Developers_Employees
foreign key ([Id]) references Employees ([Id])
This C# model and SQL Server database schema can not be changed. 不能更改此C#模型和SQL Server数据库架构。 The scenario is: 该方案是:
How should I configure my Context
class? 我应该如何配置我的Context
类? I would also appreciate sample code for this scenario. 我也希望这种情况的示例代码。
You can not do this as simple as it seems. 您不能像看起来那样简单。 You have to delete the first entity from context, clone it in a new object - Developer
here-, and add the new one to the context. 您必须从上下文中删除第一个实体,将其克隆到一个新对象(此处为Developer
,然后将新实体添加到上下文中。
var emp = _context.Employees.Find(id);
_context.Delete(emp);
var dev = new Developer(/* clone from emp */);
_context.Developers.Add(dev);
_context.SaveChanges();
Which will change the Id
of employee. 这将更改员工的Id
。 However, if you want to avoid this (changing Id
), you have to use raw SQL - eg calling a stored procedure - to add a row to Developers
and reload the context. 但是,如果要避免这种情况(更改Id
),则必须使用原始SQL(例如,调用存储过程)将行添加到Developers
并重新加载上下文。
Another option is to set Id
column by custom, which as you mentioned in Q, it's not possible to change the scheme. 另一个选项是通过自定义设置Id
列,正如您在Q中提到的那样,无法更改方案。 So ignore it. 因此,请忽略它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.