Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.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# 所需关系的可选项_C#_Sql_Sql Server_Entity Framework - Fatal编程技术网

C# 所需关系的可选项

C# 所需关系的可选项,c#,sql,sql-server,entity-framework,C#,Sql,Sql Server,Entity Framework,我有下面的型号 public class Parent { public int Id { get; set; } public string Name { get; set; } public Child LastChild { get; set; } public virtual ICollection<Child> Children { get; set; } } public class Child { public int Id

我有下面的型号

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Child LastChild { get; set; }
    public virtual ICollection<Child> Children { get; set; } 
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int ParentId { get; set; }
    public Parent Parent { get; set; }
}
公共类父类
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共子LastChild{get;set;}
公共虚拟ICollection子项{get;set;}
}
公营儿童
{
公共int Id{get;set;}
公共字符串名称{get;set;}
public int ParentId{get;set;}
公共父级{get;set;}
}
我想做的是建立两种关系:

  • 单亲多子女
  • 一个家长和可选的一个孩子
现在,我有了模型生成器的以下代码:

modelBuilder.Entity<Child>()
            .HasKey(child => child.Id);

modelBuilder.Entity<Parent>()
            .HasKey(parent => parent.Id)
            .HasMany(parent => parent.Children)
            .WithRequired(child => child.Parent)
            .HasForeignKey(child => child.ParentId);

modelBuilder.Entity<Parent>()
            .HasOptional(parent => parent.LastChild)
            .WithRequired(children => children.Parent);
modelBuilder.Entity()
.HasKey(child=>child.Id);
modelBuilder.Entity()
.HasKey(parent=>parent.Id)
.HasMany(parent=>parent.Children)
.WithRequired(child=>child.Parent)
.HasForeignKey(child=>child.ParentId);
modelBuilder.Entity()
.has可选(parent=>parent.LastChild)
.WithRequired(children=>children.Parent);
一对多关系不会导致任何问题,但零或一对一会导致以下异常:

Parent_LastChild_Target::多重性在关系“Parent_LastChild”中的角色“Parent_LastChild_Target”中无效。因为依赖角色属性不是键属性,所以依赖角色的多重性上限必须为“*”


这种关系在实体框架下可能吗?如果是这样的话,我如何才能实现所需的关系呢?

我对EF的了解还不够,不知道它是否支持,但我想知道为什么您没有将属性LastChild设置为如下所示:
public Child LastChild{get{return Children.LastOrDefault();}
EF中的导航属性可以是
可选的(即0..1到x)、必需(即1到x)或多个(即*到x)
@MarcelGosselin我这样做主要是为了更好的性能,问题中的模型只是一个例子。在真实的模型中,每个家长都将有数千个孩子。其中一个详细信息页面旨在显示最新的活动,如果在整个“孩子”表中枚举,以找到第一个与该活动相关的孩子,那将是一种浪费父项。@Avijit不表示
x
表示
可选、必需和多个
x
表示
多个