Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建双向1:0..1关系_C#_Entity Framework - Fatal编程技术网

C# 创建双向1:0..1关系

C# 创建双向1:0..1关系,c#,entity-framework,C#,Entity Framework,我试图从现有的数据库创建一个模型,我注意到了一个问题 我有下列表格 User ---------------- <pk> userId <fk> profileId Profile ---------------- <pk> profileId 但实际上,个人资料是这样的 public class User { public int userId {get; set;} public virtual Profile Profile { get

我试图从现有的数据库创建一个模型,我注意到了一个问题

我有下列表格

User
----------------
<pk> userId
<fk>  profileId

Profile
----------------
<pk> profileId
但实际上,个人资料是这样的

public class User
{
   public int userId {get; set;}
   public virtual Profile Profile { get; set; }
}

public class profile
{
   public int profileId {get; set;}
   public virtual User User { get; set; }
}
public class profile
{
   public int profileId {get; set;}
   public virtual ICollection<User> User { get; set; }
}
User
----
<pk>Id
userName

Profile
----
<pk><fk>UserId
profileName
公共类配置文件
{
公共int profileId{get;set;}
公共虚拟ICollection用户{get;set;}
}
实体认为一个概要文件可以有很多用户,因为概要文件没有用户ID。因此,我在用户表中的
profileId
上创建了一个唯一的索引(忽略空值),但仍然存在相同的问题

如何使用数据库优先方法在实体中创建1:0..1关系


谢谢

实体框架不理解用户表的profileId上的唯一键隐式指定1:0..1关系

如果您真的想对Entity Framework能够理解的1:0..1关系建模,那么profile表没有理由拥有自己的键。您可以简单地重用用户表中的键。在这种情况下,profileId列同时成为主键和外键(指向用户表的userId)。最终的数据库方案如下所示

public class User
{
   public int userId {get; set;}
   public virtual Profile Profile { get; set; }
}

public class profile
{
   public int profileId {get; set;}
   public virtual User User { get; set; }
}
public class profile
{
   public int profileId {get; set;}
   public virtual ICollection<User> User { get; set; }
}
User
----
<pk>Id
userName

Profile
----
<pk><fk>UserId
profileName
用户
----
身份证件
用户名
轮廓
----
用户ID
档案名称

这不是一种0对1的关系。这是一个简单的1对1模型,但是您已经建立了1对n模型(任何用户都可以引用任何概要文件,因此某个概要文件可以被许多用户引用)。你为什么有个人资料id?
userId
作为PK和FK就足够了。那么EF可能得到了正确的映射。我不明白没有profileID它怎么能工作。你能解释一下吗。此外,用户表中还有一个唯一的profileId索引。因此,最终没有人可以拥有相同的概要文件,不管列如何命名。基本点是配置文件的PK是用户PK的FK,但profileId是外键。这两个表之间存在关系,只需删除
User.profileId
列(连同FK约束),并将
Profile.profileId
的FK约束添加到
User.userId
。这是指定1对1关系的自然方式。我在尝试创建用户时出错。它表示无法确定类型“user”和“profile”之间关联的主体端。必须使用关系fluent API或数据注释显式配置此关联的主体端。我不明白为什么,因为模型说引用约束user->profile,关系看起来很好(1-0..1)。