Entity framework conditional entity relation

1.3k views Asked by At

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 SourceTypes are A and B. how do i make entity relation in Notification according to the type of Source?

I used linq join on every query to join the related entites according to sourcetypes for now.

I am doing database first model.

1

There are 1 answers

8
Marc Cals On

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

public virtual Notification { get; set; }

And then create 0..1 to many Relation in you Entity Framework configuration

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

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