简体   繁体   English

实体框架条件实体关系

[英]Entity framework conditional entity relation

UPDATED 更新

I have a Notification table as 我有一个通知表

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; }
}

and there are two source tables 并且有两个源表

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;}
}

In modelbuilder 在模型构建器中

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

       modelBuilder.Entity<SourceB>()
            .HasOptional(c => c.Notification)
            .WithRequired(x => x.B);

This is my new query 这是我的新查询

var myNotification = db.Notifications.Select(x => new Notification()
            {
                A= x.A,
                B= x.B,
                SourceID = x.SourceID,    
            }).ToList(); //error

I am getting this error The entity or complex type 'Notification' cannot be constructed in a LINQ to Entities query 我收到此错误The entity or complex type 'Notification' cannot be constructed in a LINQ to Entities query

The SourceTypes are A and B . SourceTypesAB how do i make entity relation in Notification according to the type of Source? 如何根据Source的类型在Notification建立实体关系?

I used linq join on every query to join the related entites according to sourcetypes for now. 我现在在每个查询上使用linq join来根据源类型连接相关实体。

I am doing database first model . 我正在做数据库优先模型

You can do it creating a relation 0..1 to many In SourceA and SourceB you have to add a property to reference to Notification Parent 您可以创建与许多对象的关系0..1。在SourceA和SourceB中,您必须添加一个属性以引用Notification Parent

public virtual Notification { get; set; }

And then create 0..1 to many Relation in you Entity Framework configuration 然后在您的实体框架配置中创建0..1到多个关系

HasOptional(x => x.SourceA) .WithRequired(s => s.Notification);

HasOptional(x => x.SourceB) .WithRequired(s => s.Notification);

Query error 查询错误

You can't do a Select with a new in a Query that is executed in Database, this only work in memory collections, to have the value of SourceID you can do something like 您不能对在数据库中执行的查询中的新内容执行Select操作,这仅适用于内存集合,要获得SourceID的值,您可以执行以下操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM