LINQ query cannot be translated if DbContext is wrapped in an interface
-
03-07-2021 - |
Вопрос
I'm having a nasty problem I really can't understand.
Basically I have a DbContext defined as follows
public interface ISettingsContext : IDisposable
{
IDbSet<Site> Sites { get; }
IDbSet<SettingGroup> Groups { get; }
IDbSet<SettingProperty> Properties { get; }
int SaveChanges();
}
public class SettingsContext : DbContext, ISettingsContext
{
public SettingsContext(string connectionStringName) : base(connectionStringName)
{
Sites = Set<Site>();
Groups = Set<SettingGroup>();
Properties = Set<SettingProperty>();
}
public SettingsContext() : this("DefaultTestConnectionString") { }
public IDbSet<Site> Sites { get; private set; }
public IDbSet<SettingGroup> Groups { get; private set; }
public IDbSet<SettingProperty> Properties { get; private set; }
#region Model Creation
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
MapSite(modelBuilder.Entity<Site>());
MapGroup(modelBuilder.Entity<SettingGroup>());
MapProperty(modelBuilder.Entity<SettingProperty>());
MapValue(modelBuilder.Entity<SiteSettingValue>());
MapXmlValue(modelBuilder.ComplexType<XmlValue>());
MapXmlType(modelBuilder.ComplexType<XmlTypeDescriptor>());
}
private void MapXmlType(ComplexTypeConfiguration<XmlTypeDescriptor> complexType)
{
complexType.Ignore(t => t.Type);
}
private void MapXmlValue(ComplexTypeConfiguration<XmlValue> complexType)
{
complexType.Ignore(t => t.Value);
}
private void MapValue(EntityTypeConfiguration<SiteSettingValue> entity)
{
entity.HasKey(k => new { k.PropertyId, k.SiteId }).ToTable("SiteValues", "settings");
entity.Property(k => k.PropertyId).HasColumnName("FKPropertyID");
entity.Property(k => k.SiteId).HasColumnName("FKSiteID");
entity.Property(k => k.Value.RawData).HasColumnName("Value").IsMaxLength();
entity.HasRequired(k => k.Site).WithMany(s => s.Settings).HasForeignKey(k => k.SiteId);
entity.HasRequired(k => k.Property).WithMany().HasForeignKey(k => k.PropertyId);
}
private void MapProperty(EntityTypeConfiguration<SettingProperty> entity)
{
entity.HasKey(k => k.Id).ToTable("Properties", "settings");
entity.Property(k => k.Id);
entity.Property(k => k.Name);
entity.Property(k => k.GroupId).HasColumnName("FKGroupID");
entity.Property(k => k.PropertyDescriptor.RawData).HasColumnName("TypeDescriptor").IsMaxLength();
entity.Property(k => k.DefaultValue.RawData).HasColumnName("DefaultValue").IsMaxLength();
entity.HasRequired(k => k.Group).WithMany(k => k.Properties).HasForeignKey(k => k.GroupId);
}
private void MapGroup(EntityTypeConfiguration<SettingGroup> entity)
{
entity.HasKey(k => k.Id).ToTable("Groups", "settings");
entity.Property(k => k.Id);
entity.Property(k => k.Name);
entity.HasMany(k => k.Properties).WithRequired(k => k.Group).HasForeignKey(k => k.GroupId);
}
private void MapSite(EntityTypeConfiguration<Site> entity)
{
entity.HasKey(k => k.Id).ToTable("Sites", "site");
entity.Property(k => k.Id);
entity.Property(k => k.Domain);
}
#endregion
}
Since I was carrying on some tests, I started working on this context without caring about IoC and DI, so I worked directly against the concrete class itself.
So I wrote this query:
public class SiteSettingsLoader : ILoader<SiteSettingsModel, int> {
...
var qSiteValues = from site in context.Sites
let settings = site.Settings
select new
{
SiteId = site.Id,
Settings = from value in settings
join property in context.Properties on value.PropertyId equals property.Id into props
from property in props
select new
{
PropertyId = property.Id,
Name = property.Name,
GroupId = property.GroupId,
Value = value.Value,
CanBeInherited = property.CanBeInherited
}
};
And everything worked just fine. The problems started when I started passing the context as the interface it implements instead of its real type.
using (ISettingsContext context = new SettingsContext())
using (SiteSettingsLoader loader = new SiteSettingsLoader(context))
{
SiteSettingsStore store = new SiteSettingsStore(loader);
dynamic settings = store.GetItem(1);
}
This is the error
Unable to create a constant value of type 'Settings.Entities.SettingProperty'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
How is it possible? Did Microsoft play some dirty trick with reflection?
EDIT: Both XmlValue and XmlTypeDescriptor are an implementation of the following interface that we use to automatically read the content of an XML field into a proper object.
public interface IXmlProperty
{
string RawData { get; set; }
void Load(string xml);
XDocument ToXml();
}
Basically we map the content of the field to the RawData property; in its setters and getters we parse/generate the string containing the XML for the database. I know it's an ugly trick but it works and gets the job done.
Решение
Based on this answer to a very similar question the reason for the problem seems to be that EF does not understand the properties of your custom interface type as queryable expressions and considers the context.Properties
collection as a collection of constant objects of type SettingsProperty
that you want to pass into the query. Using non-primitive constant objects is not supported by EF which causes your exception.
Basically you need to use a (compile time) type that EF knows how to translate into a SQL fragment to incorporate into the whole query. That would be a DbContext.DbSet<T>
itself or an IQueryable<T>
:
IQueryable<SettingProperty> properties = context.Properties;
var qSiteValues = from site in context.Sites
let settings = site.Settings
select new
{
SiteId = site.Id,
Settings = from value in settings
join property in properties
on value.PropertyId equals property.Id
into props
from property in props
select new
{
PropertyId = property.Id,
Name = property.Name,
GroupId = property.GroupId,
Value = value.Value,
CanBeInherited = property.CanBeInherited
}
};
It might be necessary to use the same trick for context.Sites
but I am not sure.
(If the above works don't forget to upvote Eranga's linked answer because it's awesome.)