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# 实体框架条件实体关系_C#_Entity Framework_Entity Framework 6_Entity Relationship - Fatal编程技术网

C# 实体框架条件实体关系

C# 实体框架条件实体关系,c#,entity-framework,entity-framework-6,entity-relationship,C#,Entity Framework,Entity Framework 6,Entity Relationship,更新 我有一个通知表 public class Notification { public int SourceType { get; set; } public int SourceID { get; set; } .... // Relations public virtual SourceA A { get; set; } public virtual SourceB B { get; set; } } 有两个源表 public class Sourc

更新

我有一个通知表

public class Notification
{
   public int SourceType { get; set; }
   public int SourceID { get; set; }
   ....
   // Relations
   public virtual SourceA A { get; set; }
   public virtual SourceB B { get; set; }
}
有两个源表

public class SourceA
{
   public int Id { get; set; }
   ...
   public virtual Notification {get; set;}
}
public class SourceB
{
   public int Id { get; set; }
   ...
   public virtual Notification {get; set;}
}
在modelbuilder中

       modelBuilder.Entity<SourceA>()
            .HasOptional(c => c.Notification)
            .WithRequired(x => x.A);

       modelBuilder.Entity<SourceB>()
            .HasOptional(c => c.Notification)
            .WithRequired(x => x.B);
我收到此错误。无法在LINQ to Entities查询中构造实体或复杂类型“Notification”

源类型为A和B。如何根据源类型在通知中建立实体关系

目前,我在每个查询中使用LINQJOIN根据sourcetypes连接相关的实体


我正在做数据库优先模型。

您可以创建一个0..1到多的关系 在SourceA和SourceB中,必须添加属性以引用通知父对象

公共虚拟通知{get;set;}

然后在实体框架配置中创建0..1对多关系

HasOptionalx=>x.SourceA .WithRequireds=>s.通知

HasOptionalx=>x.SourceB .WithRequireds=>s.通知

查询错误

在数据库中执行的查询中,不能使用new进行选择,这只能在内存集合中工作,要获得SourceID的值,可以执行如下操作


public int SourceID{get return SourceA=!null?SourceA.ID:SourceB.ID;}

一个对象可以具有这两个关系,或者是互斥的?只能有一个?这里的SourceType的关系在哪里?@Ruchan SourceType不必保存在数据库中,它可以是一个计算属性,如“public int SourceType{get{if SourceA==!null{return X}else if SourceB!=null{return Y;}”SourceA和SourceB有公共字段,它们可以像层次结构一样实现吗?使用LazyLoading来获取SourceA或SourceB的结果。SourceA和SourceB完全不同,没有层次结构。我尝试过延迟加载,但在选择通知时出现了类似“无法创建模型通知”的错误
var myNotification = db.Notifications.Select(x => new Notification()
            {
                A= x.A,
                B= x.B,
                SourceID = x.SourceID,    
            }).ToList(); //error