开发者

Linq mapping between models

I have a data-model for Entity Framework in which some entities have a collection of attributes that can be used to add extra information. Some clients would like to map these attributes to 'real' properties of their own domain-model. An example data-model is:

public class DataEntity {  
   public Guid Id { get; set; }
   public virtual ICollection<Attribute>开发者_开发知识库 Attributes { get; set; }
}
public class DataAttribute {
   public Guid Id { get; set; }
   public String Name { get; set; }
   public String Value { get; set; }
}
public class DataStringAttribute : DataAttribute {
   public String Value { get; set; }
}
public class DataInt32Attribute : DataAttribute {
   public Int32 Value { get; set; }
}

And an example domain-model is:

public class DomainEntity {
    public Guid Id { get; set; }
    public String Name { get; set; }
    public Int32 Age { get; set; }  
}

I can fairly easily map the entities between eachother, but I would like to be able to map Linq expressions between the two so that in the client, it would be IQueryable<DomainEntity>, but this is mapped to IQueryable<DataEntity> - for example:

myDomainEntities.Where(o => o.Age > 21)

could be mapped to:

myDataEntities.Where(o => o.Attributes.OfType<DataInt32Attribute>()
    .Any(o => o.Name = "Age" && o.Value > 21);

What would be the best way to do this - perhaps write a QueryProvider that walks the expression tree and translates it to one that uses the Data model - a Linq-to-Linq-to-EntityFramework?

Thanks.


What you are trying to do is atypical. You might need to override the Linq-to-Entity provider and override its query-generation functionality. You'll be walking the expression tree yourself and then dynamically converting that expression tree to a new tree that Linq-to-Entity can work with, then pass that tree to the original provider for query-generation.

In other words, you are hijacking Linq-to-Entity to support your custom format. Hairy, but if you get it working, please write about it! I'd be glad to learn how it works!

Also, you understand that your client will not get Intellisense support though, unless you write you custom plugin for VS also. The code will also be flagged as syntax errors in VS (I am not sure whether it will compile). That is because the class definitions really didn't change -- the entities didn't really have those properties.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜