score:0
Depending on how many classes we're talking about, and how flexible you need to be, interfaces might not be out of the question. I've done something similar using generics:
//WARNING: Partially-remembered code ahead...
interface IDuckEntity
{
int FeatherCount { get; set; }
}
public partial class Products1 : IDuckEntity { }
public partial class Products2 : IDuckEntity { }
public partial class Products3 : IDuckEntity { }
//in some other class:
void DoStuff<T>(T entity) where T : EntityObject, IDuckEntity
{
entity.FeatherCount = 500;
}
So basically, you set up a separate file where you put the interface and a bunch of those little partial class declarations. Then you'll have access to the common structure. I don't know what your exact situation is, but this worked like a charm for me.
score:1
Since the EF4 classes are partial classes you can actually extend them and make them implement an interface of your choice, all in a separate file.
An alternative to that would be using dynamic
- just instantiate the entity based on it's type.
dynamic myEntity= Activator.CreateInstance(Type.GetType("EntityTypeHere")));
myEntity.CommonProperty = "Foo";
The big disadvantage here is that you lose all type safety at compile time - any problem you will only discover at runtime, also it's slower than the statically typed approach.
score:2
You could build an Expression tree to query for the object or objects in question:
public T GetSingleObject<T>(int someValue) {
MyEntities db = new MyEntities();
var result = db.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name + "s"));
var param = Expression.Parameter(typeof(T));
var lambda = Expression.Lambda<Func<T, bool>>(
Expression.Equal(
Expression.Property(param, "WhateverPropertyYourComparing"),
Expression.Constant(someValue)),
param);
return result.SingleOrDefault(lambda);
}
Or if you want a collection of objects
public IEnumerable<T> GetResultCollection<T>(int someValue) {
MyEntities db = new MyEntities();
var result = db.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name + "s"));
var param = Expression.Parameter(typeof(T));
var lambda = Expression.Lambda<Func<T, bool>>(
Expression.Equal(
Expression.Property(param, "WhateverPropertyYourComparing"),
Expression.Constant(someValue)),
param);
return result.Where(lambda);
}
Of course if your desired query is very long, this can get out of hand, and you should consider adding in the necessary interface using partial classes, as Justin Morgan suggested.
Note that this method assumes that your ObjectSet collection is the same name as your object, plus an "s", ie, "Invoice" to "Invoices". If that's not the case, ie, "Person" to "People", then you could use System.Data.Entity.Design.PluralizationServices.PluralizationService to get the proper name
Source: stackoverflow.com
Related Articles
- Retrieving an Entity Object by name - LINQ to Entities, EF 4.0
- LINQ querying using an entity object not in the database - Error: LINQ to Entities does not recognize the method
- C# Initialize an inherent object and get error "The entity cannot be constructed in a LINQ to Entities query"
- Entity Framework 4 and Linq to Entities specifications: How to code it?
- Entity Framework Code First - The entity or complex type cannot be constructed in a LINQ to Entities query
- Entity framework linq query Include() multiple children entities
- The LINQ expression node type 'Invoke' is not supported in LINQ to Entities in entity framework
- Linq to SQL: How do I stop the auto generated object name from being renamed?
- LINQ to Entities only supports casting Entity Data Model primitive types?
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- Linq To SQL Attach/Refresh Entity Object
- LINQ to SQL entity column name attribute ignored with guid primary key
- Entity Framework LINQ Expression on object within object
- The entity or complex type ... cannot be constructed in a LINQ to Entities query
- LINQ to Entities - How to return a single string value from entity
- Retrieve single Entity Framework entities using a LINQ query or GetObjectKey?
- Replicating LINQ to Entities behavior in unit tests that use LINQ to Object
- Problem with LINQ to Entities query using Sum on child object property
- Object functions fail within LINQ to Entities Expressions
- The entity or complex type cannot be constructed in a LINQ to Entities query
- Linq to entities - SQL Query - Where list contains object with 2 properties (or more)
- Using Specification Pattern and Expressions in Entity Framework and Linq to Entities
- LINQ Source Code Available
- Entity Framework 'ArrayIndex' is not supported in LINQ to Entities
- Linq with where clause in many-to-many EF Code First object
- Internal access for entities in Entity Framework makes simple linq where query crash
- Refactor Linq code and "LINQ to Entities does not recognize the method"
- EF Linq to Entities calling ToList() on entity set generates SQL command containing multiple left outer join
- Using LINQ how do I create a List of one particular field of an entity from a collection entities
- Linq to entities does not recognize my entity types
- Linq sorting with nullable object
- Convert DataTable to String Array through Extension Method
- ValueInjecter - Joins multiple result sets into 1 collection LINQ?
- Find all child controls of specific type using Enumerable.OfType<T>() or LINQ
- Subquery in Linq
- Sum and subtract using Linq C#
- Change long if statement to LINQ
- MVC Data Annotation - Required Field not Working
- Logging all Entity Framework queries in the debug window in DB-First Approach
- Using Any to check against a list in NHibernate
- Fastest way to fill DataTable from LINQ query using DataContext
- Selecting IEnumerable from JOIN results in a complex Linq-to-SQL query
- Invalid Cast Exception DBQuery LINQ
- LINQ - get element within element
- Select Max Date in Linq Join Query
- Save picture Path with LINQ in SQL
- Getting attributes from xml using Linq
- Refresh DataSource after SaveChange does not work
- optimization or alternate of linq (for aggreation) C#
- Array substring in deferred execution