Entity Framework and generics - c#

I have a couple independent objects, each of which has a list of a common object. For instance,
public class Project
{
public IEnumerable<CommentEntry<Project>> Comments{get;set;}
}
public class Sample
{
public IEnumerable<CommentEntry<Sample>> Comments{get;set;}
}
public class CommentEntry<T> where T: class
{
public int TId {get;set;}
public int CommentEntryId{get;set;}
public DateTime TimeStamp{get;set;}
public string Comment{get;set;}
}
Using fluent api of Entity Framework 5, I would like a CommentEntry table for Projects and Requests. So, here is my mapping code:
modelBuilder.Entity<CommentEntry<Project>>()
.Map(m =>
{
m.ToTable("EngineeringProjectComments");
});
modelBuilder.Entity<CommentEntry<Request>>()
.Map(m =>
{
m.ToTable("SampleRequestComments");
});
When I attempt my migration I encounter the following message:
The type CommentEntry`1[Project]' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.
I can see the obvious flaw of my attempt to use generics in this context. However, can anyone suggest an alternative to my database table structure, classes code or mapping code that will allow me to share the single, generic type among many classes and have independent tables?

Just use the normal inheritance structure. And, instead of using a specific ID name, like EngineeringProjectId, just use Id.
public class Project
{
public ICollection<ProjectCommentEntry> Comments{get;set;}
}
public class Sample
{
public ICollection<SampleCommentEntry> Comments{get;set;}
}
public class ProjectCommentEntry : CommentEntry {}
public class SampleCommentEntry : CommentEntry {}
public class CommentEntry
{
public int Id {get;set;}
public int CommentEntryId{get;set;}
public DateTime TimeStamp{get;set;}
public string Comment{get;set;}
}
By the way, you can't use IEnumerable for navigation properties in EF, you need a full collection which is why you should use ICollection instead.

Related

Can C# constraints be used without a base type?

I have some classes with common properties, however, I cannot make them derive from a base type (LINQ-to-SQL limitations).
I would like to treat them as if they had a base type, but not by using Reflection (performance is critical).
For example:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
}
public class Vehicle
{
public int Id { get; set; }
public string Label { get; set; }
}
In this case I would be happy if I had the Id property available, regardless of the type I'm holding.
Is there any way in C# to to something similar to this:
public static int GetId<T>(T entity) where T // has an int property 'Id'
{
return entity.Id;
}
I guess I could have used dynamic, however, I'm looking for a way to restrict the code in compile time from using this method for an object that has no Id property.
You can use interfaces:
public interface IHasId
{
int Id { get; }
}
public class User : IHasId { ... }
public class Vehicle : IHasId { ... }
public static int GetId<T>(T entity) where T : IHasId
{
return entity.Id;
}
However, if you are not able to modify the classes to add the interface, you won't be able to do this. No compile-time checks will verify that a property exists on T. You'd have to use reflection - which is slow and obviously not ideal.
There is no way to guarantee a type has a given member without constraining to a common base type or interface. One way to work around this limitation is to use a lambda to access the value
public static int Use<T>(T value, Func<T, int> getIdFunc) {
int id = getIdFunc(value);
...
}
Use(new User(), u => u.Id);
Use(new Vehicle(), v => v.Id);
You can create an interface with the common properties and make your classes implement it:
public interface IEntity
{
int Id { get; set; }
}
public class User : IEntity
{
public int Id { get; set; }
public string FirstName { get; set; }
}
public class Vehicle : IEntity
{
public int Id { get; set; }
public string Label { get; set; }
}
public static int GetId<T>(T entity) where T : IEntity
{
return entity.Id;
}
You could simplify GetId like this:
public static int GetId(IEntity entity)
{
return entity.Id;
}
The other answers mentioning the interface approach are certainly good, but I want to tailor the response to your situation involving Linq-to-SQL.
But first, to address the question title as asked
Can C# constraints be used without a base type?
Generally, the answer is no. Specifically, you can use struct, class, or new() as constraints, and those are not technically base types, and they do give some guidance on how the type can be used. That doesn't quite rise to the level of what you wish to do, which is to limit a method to types that have a certain property. For that, you will need to constrain to a specific interface or base class.
For your specific use case, you mention Linq-to-SQL. If you are working from models that are generated for you, then you should have options to modify those classes without modifying the generated model class files directly.
You probably have something like
// code generated by tool
// Customer.cs
public partial class Customer // : EntityBaseClasses, interfaces, etc
{
public int ID
{
get { /* implementation */ }
set { /* implementation */ }
}
}
And other similar files for things such as Accounts or Orders or things of that nature. If you are writing code that wishes to take advantage of the commonly available ID property, you can take utilize the partial in the partial class to define a second class file to introduce a common interface type to these models.
public interface IIdentifiableEntity
{
int ID { get; }
}
And the beauty here is that using it is easy, because the implementation already exists in your generated models. You just have to declare it, and you can declare it in another file.
public partial class Customer : IIdentifiableEntity { }
public partial class Account : IIdentifiableEntity { }
// etc.
This approach has proven valuable for me when using a repository pattern, and wishing to define a general GetById method without having to repeat the same boilerplate in repository after repository. I can constrain the method/class to the interface, and get GetById for "free."
Either you need to make both classes implement an interface with the properties you need, and use that in the generic constraint, or you write separate methods for each type. That's the only way you'll get compile-time safety.

NotMapped Error in EF5 and .NET 4.5

In VS2012(.NET 4.5 and Entity Framework 5 )
When exposed the inheritance relationship,caused the compile-time errors:
You cannot use Ignore method on the property 'InnerString' on type
'MrTree.SubSubClass' because this type inherits from the type
'MrTree.BaseClass' where this property is mapped. To exclude this
property from your model, use NotMappedAttribute or Ignore method on
the base type.
The code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyDbcontext db = new MyDbcontext();
int i = db.SubSubClasses.Count();
}
}
public class BaseClass
{
[NotMapped]
public string InnerString { get; set; }
}
public class SubClass : BaseClass
{
}
public class SubSubClass : SubClass
{
}
public class MyDbcontext : DbContext
{
public DbSet<SubSubClass> SubSubClasses { get; set; }
public DbSet<SubClass> SubClasses { get; set; }
}
}
Can you tell me what's wrong?
I have found a work around for this issue I have experienced myself. I did post some supplementary information about what might be causing the issue but it was deleted by some egotistical nerd who felt it wasn't worthy.
So here is my ANSWER to this problem - might not be entirely right but it works for me so please don't delete this Mr Nerd just in case it helps out someone else.
Firstly, this issue only affects classes that do not inherit the abstract class using the NotMapped attribute directly but instead those that inherit from another class that itself inherits from the base class, as per the original statement.
The following works for me using something similar to the following class setup:
BASE CLASS:
public abstract class EntityBase
{
public virtual int Id { get; set; } // this will be mapped
public virtual int DoNotMap { get; set; } // this should be ignored
}
FIRST LEVEL INHERITANCE
public class Contact : EntityBase
{
public string Name { get; set; }
}
SECOND LEVEL INHERITANCE
public class Employee : Contact
{
public DateTime StartDate { get; set; }
}
Create a generic configuration class that inherits from EntityTypeConfiguration:
public class DataEntityBaseConfiguration<T>
: EntityTypeConfiguration<T> where T : EntityBase
{
public DataEntityBaseConfiguration()
{
Ignore(x => x.DoNotMap);
}
}
Create configuration classes for all first level inheritance that inherit directly from the EntityBase class, i.e.:
public class ContactConfiguration : DataEntityBaseConfiguration<Contact>
{
// place any further configuration rules in the constructor
}
WORKAROUND: any classes that inherit from the EntityBase indirectly, simply create a Configuration class that inherits from EntityTypeConfiguration:
public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
// place any further configuration rules in the constructor
}
In your DataContext, in the OnModelCreating method, add you configurations:
modelBuilder.Configurations.Add(new ContactConfiguration());
modelBuilder.Configurations.Add(new EmployeeConfiguration());
Assuming a TPT approach in this instance, map the specialised version, Employee to its own table with an FK relation to Contact:
modelBuilder.Entity<Contact>().Map<Employee>(m => m.ToTable("Employees"));
This, for me at least, creates a contact table without the "DoNotMap" property and an Employee table without the "DoNotMap" table and with a PK/FK relation to Contact. Even though I do not inherit from the EntityBaseConfiguration for Employee Configuration, it still, somehow, picks up Ignore and leaves it out.
I would assume that if we went with a TPH approach, we would simply end up with a single Contact table plus Discriminator column. TPC would obviously recreate all the Contact properties in the Employee table but I'm not sure if it would also create the DoNotMap property - will test that when I have a moment spare.
In short, going back to the original question, I'm not sure why this happens with both the NotMapped attribute and the Ignore. I was getting the error when my EmployeeConfiguration inherited from the EntityBaseConfiguration. I'm not keen on the workaround as it firstly the error is false in its statement and secondly, it's a an error that would easy to fall into again, even if the solution is now quite simple.
Hope that helps anyone that has struggled with this inheritance issue.
Regards
The fact that the primary key has to be included in the POCO class definition A already means that Ais not a POCO object. You cannot ignore properties on POCO objects
Do you have a property called InnerString in your SubSubClass? That's what the error is saying, although you don't have it listed in your example code.
Your code above worked for me, but I had to add a PK, here's the entire Console app:
public class BaseClass
{
public int Id { get; set; }
[NotMapped]
public string InnerString { get; set; }
}
public class SubClass : BaseClass
{
}
public class SubSubClass : SubClass
{
}
public class MyDbcontext : DbContext
{
public DbSet<SubSubClass> SubSubClasses { get; set; }
public DbSet<SubClass> SubClasses { get; set; }
}
class Program
{
static void Main( string[] args )
{
var context = new MyDbcontext();
context.SubSubClasses.Add(new SubSubClass());
context.SaveChanges();
}
}
And the database it created:

implementing similar classes (data entity objects)

I am working on an application which currently creates data entity objects from the results of a sql query. In the database 3 of the tables are very similar but have several different properties.
My initial plan was to create 3 different classes, even though each class is very similar. However when I came to create the method which returns a list of objects, I have hit a stumbling block as the return type will be different depending on which mode the application is in.
e.g.
public class A
{
public int Id {get;}
public string Name {get;}
}
public class B
{
public int Id {get;}
public string Name {get;}
public string ExtraInfo {get;}
}
public class MainScreen
{
...
this.resultsGrid.DataSource = LoadData();
}
I would prefer not to write one method to load a list of each data type.
What should the return type of LoadData() be, to allow it to be generic as possible.
What is the most elegant way of dealing with this scenario?
Thanks,
Sean
You should have inheritance to allow polymorphism, so you would have a base class that all entities included in the data binding derive from it.
Then, you can have a mid-base class to have some shared properties like Name and ID.
Base class:
public abstract class Entity
{
}
Entity with Name and ID:
public class NameAndIDEntity : Entity
{
public int Id { get; set; }
public string Name { get; set; }
}
Entity with Name, ID and ExtraInfo:
public class NameIDAndExtraEntity : NameAndIDEntity
{
public string ExtraInfo { get; set; }
}
Entity with other information (can't be derived from NameAndIDEntity), derives from Entity so it can be included in the data binding:
public class OtherInformationEntity : Entity
{
public int Age { get; set; }
}
Finally, you can make the LoadData return type Entity.
Simples!
Create a class ListItem (with properties Id and Name, I presume). In your factory class/method, make instances of that class from the records into a List and bind the datasource to the list.
Don't be scared to create specialised classes for your UI.
UPDATE: Forgot to mention. Avoid inheritance as much as possible.
First you can create an inheitance tree in your project, where base class holds a shared/common properties among set of dfferent types
Second you can retrieve from the query anonymous type and after map it to a known type by mapping them to a real type, like from Jon Skeet's blog Horrible grotty hack: returning an anonymous type instance
That means that you need by the way know which query what type returns (can not avoid that), but this can reduce amount of fraction you need to add to your code, like from example:
static class GrottyHacks
{
internal static T Cast<T>(object target, T example) //CAST TO SPECIFIED TYPE
{
return (T) target;
}
}
class CheesecakeFactory
{
static object CreateCheesecake()
{
return new { Fruit="Strawberry", Topping="Chocolate" };
}
static void Main()
{
object weaklyTyped = CreateCheesecake(); //ANONYMOUS TYPE GENERATION
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
new { Fruit="", Topping="" }); //"MAPPING"
Console.WriteLine("Cheesecake: {0} ({1})",
stronglyTyped.Fruit, stronglyTyped.Topping);
}
}

EF 4.0 generics based inheritance

I have a class like this
public abstract class BaseType<T>
{
public string Name {};
public T TypedValue {
get {
return GetTypedValue(PersistedValue);
}
};
public string PersistedValue {}
public abstract T GetTypedValue(PersistedValue);
}
then many derived classes like
public class IntegerType:BaseType<int>
{
...
}
is it possible to map this hierarchy using EF 4.0 using Table per inheritance scheme ?
Currently the generated code creates has an error because it generates a property like
public <T> ObjectSet<TypedAttribute<T>> TypedAttributes
{
get
{
return _typedAttributes ?? (_typedAttributes = CreateObjectSet<TypedAttribute<T>>("TypedAttributes")); }
}
private ObjectSet<TypedAttribute> _typedAttributes;
I don't think so because:
Inheritance mapping requires the base class to be entity in EDMX.
When inheritance is used the ObjectSet is for base type. What generic argument would you use to create an instance of ObjectSet when it has to be used to retrieve any subtype?
It can be partially achieved without inheritance (at least for POCOs). Simply model your subtypes in EDMX without base type. Then manually create POCO classes and derive them from generic base types. The only rule you have to follow is that POCO class must have the same name as entity in EDMX and it must have all its properties with accessibility set in EDMX. If you want to use change tracking properties must be marked as virtual. If you want to use lazy loading navigation properties must be virtual as well.
Example:
Suppose that I have two entities in EDMX: IntegerValue and DoubleValue. Now I defined these POCOs as follows:
public abstract class BaseType<T>
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual T Value { get; set; }
}
public class IntegerValue : BaseType<int>
{ }
public class DoubleValue : BaseType<double>
{ }
It will result in single table per sub type.

Inherited fluent nhibenate mapping issue

I have an interesting issue today!! Basically I have two classes.
public class A : B
{
public virtual new ISet<DifferentItem> Items {get;set;}
}
public class B
{
public virtual int Id {get;set;}
public virtual ISet<Item> Items {get;set;}
}
The subclass A hides the base class B property, Items and replaces it with a new property with the same name and a different type.
The mappings for these classes are
public class AMapping : SubclassMap<A>
{
public AMapping()
{
HasMany(x=>x.Items)
.LazyLoad()
.AsSet();
}
}
public class BMapping : ClassMap<B>
{
public BMapping()
{
Id(x=>x.Id);
HasMany(x=>x.Items)
.LazyLoad()
.AsSet();
}
}
However when I run my unit test to check the mapping I get the following exception:
Tests the A mapping: NHibernate.PropertyAccessException : Invalid Cast (check your mapping for property type mismatches); setter of A
----> System.InvalidCastException : Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericSet1[Item]' to type 'Iesi.Collections.Generic.ISet1[DifferentItem]'.
Anyone have any ideas?
Clearly it is something to do with the type of the collection on the sub-class. But I skimmed through the available options on the mapping class and nothing stood out as being the solution here.
Generics in c# does not support covariance, so essentially you can't have ISet<Item> and ISet<DifferentItem>. Since it's a limitation of the language you need to rethink your design. Or wait til c# 6.

Categories

Resources