Get a list of multiple types using Entity Framework - entity-framework

Using MVC4 with Entoty Framework CodeFirst I am having problems with the following scenario:
public class Survey
{
public QuestionCollection Questions {get;set;}
}
public class QuestionCollection : List<IQuestion> //Just for MVC
{ }
public class QuestionType1 : IQuestion { ... }
public class QuestionType2 : IQuestion { ... }
Seems straightforward. Now in my controller I want to get the Survey so i have:
DataContext context = new DataContext ();
var survey = context.Surveys.Include(s => s.Questions).SingleOrDefault(s => s.Id == id);
It does compile but runtime it gives me the error:
A specified Include path is not valid. The EntityType 'Survey' does not declare a navigation property with the name 'Questions'.
What am I doing wrong here?
Is there any good tutorial on this topic?

Entity Framework Code First requires that navigation collections be declared as an ICollection<T>. Also, to enable lazy loading of the associations, it should be virtual. This is because, unless otherwise specified, EF will return a proxy object wrapping your declared class. Since your original QuestionCollection property is a concrete implementation, it can't override that in the proxy and enable the navigation. Questions has to be declared as the interface.
Your concerns and requirements in EF are different than in MVC, and they aren't always compatible. If you really, really wanted QuestionCollection, you'll have to map that.
Your Surveys entity should look like this:
public class Survey
{
public virtual ICollection<Question> Questions { get; set; }
}
Also, EF can't implement entity types declared as an interface. This won't work: public virtual ICollection<IQuestion> - your individual question types must all inheirit from a common abstract or concrete instance. They can still implement the interface, but your entity type properties cannot be declared that way.
I would highly recommend going through this series of blog posts on inheritance structures in
EF.
The way you would set up your questions entities would look like this:
// You can still keep the IQuestion interface around for MVC
public abstract class Question : IQuestion
{
// ... properties ...
}
public class QuestionType1 : Question
{
// ... properties ...
}
public class QuestionType2 : Question
{
// ... properties ...
}
public class Survey
{
// Note, collection of Question, not the interface.
public virtual ICollection<Question> Questions { get; set; }
}
Depending on how exactly you want your table structure to look, the base Question class may or may not be abstract. Refer to the above blog posts to see the various options - Table per Type, Table per Hierarchy, Table per Concrete.

Have a look at this link,I think you need to set some auto policies http://forums.asp.net/t/1816051.aspx/1

Related

Code First creates int instead of enum

I want to create a enum type column named 'type' but when I reverse engineer my Code First generated DB it assigns it as an 'int'.
Here is my Enum class:
[Flags]
public enum TypeNames
{
Een = 0,
Twee = 1,
Drie = 2
}
Here is my Grounds class to create the table with the 'TypeNames'-enum. The Properties class is another table (Grounds - Properties have a TPT inheritance).
[Table("gronden")]
public partial class Grounds : Properties
{
[Column("opp")]
public double? Surface { get; set; }
[EnumDataType(typeof(TypeNames)), Column("type")]
public TypeNames Types { get; set; }
}
Any ideas of what I am missing here to get an enum-type into my DB?
According to the following answer, it appears that EnumDataTypeAttribute is only implemented for ASP.NET UI components, and not for EF usage.
Should the EnumDataTypeAttribute work correctly in .NET 4.0 using Entity Framework?
EF Core 2.1 implements a new feature that allows Enums to be stored as strings in the database. This allows data to be self-describing, which can be really helpful for long-term maintainability. For your specific case, you could simply do:
[Table("gronden")]
public partial class Grounds : Properties
{
[Column("opp")]
public double? Surface { get; set; }
[Column("type", TypeName = "nvarchar(24)")]
public TypeNames Types { get; set; }
}
You can find more detail on this page:
https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions
Also, I noticed that you have the FlagsAttribute set on your enum. Are you hoping to be able to apply multiple enum values to a single entity? This should work fine when values are persisted as an int, but will not work if storing as a MySQL ENUM or string datatype. MySQL does support a SET datatype, but it seems unlikely that EF would add support for this feature, since most other databases don't have a similar concept.
https://dev.mysql.com/doc/refman/5.6/en/constraint-enum.html
If you do indeed want to allow multiple enum values to be applied to each entity (similar to the way tags are used on Stack Overflow), you might consider creating a many-to-many relationship instead. Basically, this would mean converting the TypeNames enum into a Types table in the database, and allowing EF to generate a GroundTypes table to link them together. Here is a tutorial:
http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

Materializing an ICollection structure containing subclasses

I'm reviewing some code that was written in the EF 4 days because it stands out during performance benchmarking.
The purpose of the code is to materialize an ICollection<MyBaseClass> using Entity Framework (we're now on EF 6.1).
The code exists because references present in specific subclasses aren't materialized when retrieving
public Parent
{
public virtual ICollection<MyBaseClass>() Base { get; set; }
}
from the database, when the actual types stored are subclasses of MyBaseClass.
Example subclass:
public SubA : MyBaseClass
{
public virtual ICollection<Options> Ref1 { get; set; }
}
Currently, the code does something like this:
var parent = ctx.Parents.Include(p => p.Base).Where(...).Single();
LoadSubclasses(parent.Base);
...
private void LoadSubclasses(IEnumerable<MyBaseClass> myBase)
{
foreach (var my in myBase)
{
if (my is SubA)
{
this.Entry(my).Reference("Ref1").Load();
this.Entry((SubA)my).Ref1).Collection("Options").Load();
}
else... // Similar for other subclasses
}
}
Note that ICollection<MyBaseClass>() Base contains a mix of several concrete subclasses. There are generally a few hundred objects in the ICollection.
Is there a more efficient way to materialize Base?
It cannot be said in advance if the performance will be better (sometimes executing a single complex query, especially with sub collection includes may have actually negative impact), but you can minimize the number of database queries to K, where K is the number of subclass types that need additional includes.
You need to base the LoadSubclasses method on IQueryable<TBase> representing all base entities, and execute one query per each subclass type using OfType filter:
private void LoadSubclasses(IQueryable<MyBaseClass> baseQuery)
{
// SubA
baseQuery.OfType<SubA>()
.Include(x => x.Ref1.Options)
.Load();
// Similar for other subclasses
}
The usage with your sample would be:
var parent = ctx.Parents.Include(p => p.Base).Where(...).Single();
LoadSubclasses(ctx.Entry(parent).Collection(p => p.Base).Query());
or more generally:
var parentQuery = ctx.Parents.Where(...);
var parents = parentQuery.Include(p => p.Base).ToList();
LoadSubclasses(parentQuery.SelectMany(p => p.Base));
For those on EF Core 2.1 or later, this feature is now supported out-of-the-box.
Request from 2010:
When in an data model for entity framework has a navigation property
it is not posseble to eager load that navigation property besides when
using OfType<> or when eager loading the derived type itself by a
navigation property.
Response from 2018:
The feature is part of EF Core 2.1, which is currently in preview.
Please create issues in our issue tracker if you find any problems.

The type 'Company.Model.User' and the type 'Company.Core.Model.User' both have the same simple name of 'User' and so cannot be used in the same model

I have a base entity class MyCompany.Core.Model.User which is to be used for common properties of a User entity:
public class User
{
public string Username { get; set; }
public string Usercode { get; set; }
}
I also have a base mapping class MyCompany.Core.Model.UserMap to setup the code first mappings for the base User class:
public class UserMap<TUser> : EntityMapBase<TUser>
where TUser : User
{
public UserMap()
{
// Primary Key
this.HasKey(t => t.Usercode);
// Table & Column Mappings
this.ToTable("Users");
this.Property(t => t.Username).HasColumnName("Username");
this.Property(t => t.Usercode).HasColumnName("UserCode");
}
}
In a separate assembly I have a derived class MyCompany.Model.User that inherits from the base User class and extends it with some additional properties:
public class User : Core.User
{
public string Surname { get; set; }
}
In addition I have a derived mapping class MyCompany.Model.UserMap to provide the additional configuration for the additional properties:
public class UserMap : Core.UserMap<User>
{
public UserMap()
{
this.Property(t => t.Surname).HasColumnName("Surname");
}
}
However when adding MyCompany.Model.User to the context and registering the MyCompany.Model.UserMap I'm getting the following error:
The type 'MyCompany.Model.User' and the type 'MyCompany.Core.Model.User' both have the same simple name of 'User' and so cannot be used in the same model. All types in a given model must have unique simple names. Use 'NotMappedAttribute' or call Ignore in the Code First fluent API to explicitly exclude a property or type from the model.
This link indicates that you can't have the same "simple name" in the model twice.
Why is the base class "simple name" being registered in the model, and is there a way around it in order to implement this sort of entity inheritance?
I suspect the simple solution would be to rename the derived class; however I would prefer to avoid this as there may be many derivations in multiple contexts.
Note: Using Entity Framework 6.0.0-rc1 (prerelease)
This is a limitation of EF that I reported in 2012 https://entityframework.codeplex.com/workitem/483 that is still not implemented in 6.0.2. EF uses a flat internal architecture and does not recognize namespaces. Might be coming in EF7 but not before. For now the only solutions is to rename the two classes to unique class names irrespective of the namespace they are in. IMHO, this is an significant limitation within EF. Just consider a class named Category and how many different namespaces it could be used within across a domain.
First read Table type mappings
The hierarchical implementation model options need to be understood first.
Then look at the IGNORE option. You may or may not need depending on chosen approach.
requires ignore ???
modelBuilder.Ignore<BaseXYZ>()
Ef is currently trying to include your base class to support an included Type that inherits from a NON abstract class.
This happens also if you forget to explicitly add a namespace in your class. Running on EF 6.4.4 and i can differentiate through namespaces.
e.g.
public class MyClass {}
Instead of:
namespace somenamespace
{
public class MyClass {}
}
To keep same class name I suggest to use different interfaces. An interface for the Core.Entity defining the common properties and an other interface for the extra properties. So instead of using a derived class you use a class implementing the two interfaces.
if you have 2 or more classes with a relationship between them like this:
public class A{
public X attribute1 {get;set;}
public B b {get;set;}
}
public class B{
public X attribute1 {get;set;}
}
sometimes in this situation it raises this error,
Solution :
change X name in one class.

Entity Framework 5 table-per-type update, change sub type but keep same base type

I have a simple hierarchy
public abstract class CommunicationSupport
{
public SupportTypeEnum Type { get; set; }
public Country Origin { get; set; } // National or Foreign support
}
public class TelecomSupport : CommunicationSupport
{
public string Number { get; set; }
}
public class PostalSupport : CommunicationSupport
{
public Address Address { get; set; }
}
I plan to use the Table-per-type hierarchy for my DB. So 3 tables will be created, one base and two child using the same PK as the base.
My problem is that I want to be able to update a CommunicationSupport by changing it's type.
Let's say that I create a TelecomSupport, save it and then change it's type to a PostalSupport and save it again (update). The result I expect is for EF to keep the same base record (CommunicationSupport Id) but delete the record in the TelecomSupport table and create a new one in the PostalSupport.
So TelecomSupport and PostalSupport are exclusive and cannot share the same base CommunicationSupport.
How can I do that using EntityFramework 5?
Thanks for your help!
I don't have a good answer, but I can think of four "solutions" that are really workarounds:
Don't use DBMS-computed values for your primary keys (if you already use natural keys, it's fine).
Use DBMS-computed surrogate keys.
Follow something like the state pattern.
Do some evil voodoo with the object state manager.
Update: There seems to be a popular consensus that trying isn't even worth it; most people thus simply use stored procedures instead to work around the problem.
Changing Inherited Types in Entity Framework
Entity Framework: Inheritance, change object type
Changing the type of an (Entity Framework) entity that is part of an inheritance hierarchy
Changing the type of an entity that is part of an inheritance hierarchy
Using natural keys
First, remember that the objects tracked by the EF are part of your DAL, not your domain model (regardless of whether you use POCOs or not). Some people don't need a domain model, but keep it in mind, as we can now think of these objects as representations of table records we manipulate in ways we wouldn't with domain objects.
Here, we use IDbSet.Remove to delete the records of the entity, then add new ones with the same primary key using IDbSet.Add, all in a single transaction. See the ChangeType method in the sample code below.
In theory, integrity is OK, and in theory, EF could detect what you're trying to do and optimize things. In practice, it currently doesn't (I profiled the SQL interface to verify this). The result is that it looks ugly (DELETE+INSERT instead of UPDATE), so if system beauty and performance are issues, it's probably a no-go. If you can take it, it's relatively straightforward.
Here is some sample code I used to test this (if you want to experiment, simply create a new console application, add a reference to the EntityFramework assembly, and paste the code).
A is the base class, X and Y are subclasses. We consider Id to be a natural key, so we can copy it in the subclasses copy constructors (here only implemented for Y). The code creates a database and seeds it with a record of type X. Then, it runs and changes its type to Y, obviously losing X-specific data in the process. The copy constructor is where you would transform data, or archive it if data loss is not part of the business process. The only piece of "interesting" code is the ChangeType method, the rest is boilerplate.
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
namespace EntitySubTypeChange {
abstract class A {
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Foo { get; set; }
public override string ToString() {
return string.Format("Type:\t{0}{3}Id:\t{1}{3}Foo:\t{2}{3}",
this.GetType(), Id, Foo, Environment.NewLine);
}
}
[Table("X")]
class X : A {
public string Bar { get; set; }
public override string ToString() {
return string.Format("{0}Bar:\t{1}{2}", base.ToString(), Bar, Environment.NewLine);
}
}
[Table("Y")]
class Y : A {
public Y() {}
public Y(A a) {
this.Id = a.Id;
this.Foo = a.Foo;
}
public string Baz { get; set; }
public override string ToString() {
return string.Format("{0}Baz:\t{1}{2}", base.ToString(), Baz, Environment.NewLine);
}
}
class Program {
static void Main(string[] args) {
Display();
ChangeType();
Display();
}
static void Display() {
using (var context = new Container())
Console.WriteLine(context.A.First());
Console.ReadKey();
}
static void ChangeType()
{
using (var context = new Container()) {
context.A.Add(new Y(context.A.Remove(context.X.First())));
context.SaveChanges();
}
}
class Container : DbContext {
public IDbSet<A> A { get; set; }
public IDbSet<X> X { get; set; }
public IDbSet<Y> Y { get; set; }
}
static Program() {
Database.SetInitializer<Container>(new ContainerInitializer());
}
class ContainerInitializer : DropCreateDatabaseAlways<Container> {
protected override void Seed(Container context) {
context.A.Add(new X { Foo = "Base Value", Bar = "SubType X Value" });
context.SaveChanges();
}
}
}
}
Output:
Type: EntitySubTypeChange.X
Id: 0
Foo: Base Value
Bar: SubType X Value
Type: EntitySubTypeChange.Y
Id: 0
Foo: Base Value
Baz:
Note: If you want an auto-generated natural key, you can't let EF ask the DBMS to compute it, or EF will prevent you from manipulating it the way you want (see below). In effect, EF treats all keys with computed values as surrogate keys, even though it still happily leaks them (the bad of both worlds).
Note: I annotate the subclasses with Table because you mentioned a TPT setup, but the problem is not actually related to TPT.
Using surrogate keys
If you consider a surrogate key to be truly internal, then it doesn't matter if it changes under your nose as long as you can still access your data the same way (using a secondary index for example).
Note: In practice, many people leak surrogate keys all around (domain model, service interface, ...). Don't do it.
If you take the previous sample, simply remove the DatabaseGenerated attribute and the assignment of the Id in the copy constructor of the subtypes.
Note: With its value generated by the DBMS, the Id property is completely ignored by EF and doesn't serve any real purpose other than being analyzed by the model builder to generate the Id column in the SQL schema. That and being leaked by bad programmers.
Output:
Type: EntitySubTypeChange.X
Id: 1
Foo: Base Value
Bar: SubType X Value
Type: EntitySubTypeChange.Y
Id: 2
Foo: Base Value
Baz:
Using the state pattern (or similar)
This solution is probably what most people would consider the "proper solution", since you can't change the intrinsic type of an object in most object-oriented languages. This is the case for CTS-compliant languages, which includes C#.
The problem is that this pattern is properly used in a domain model, not in a DAL like one implemented with EF. I'm not saying it's impossible, you may be able to hack things up with complex types or TPH constructs to avoid the creation of an intermediary table, but most likely you'll be swimming up the river until you give up. Hopefully someone can prove me wrong though.
Note: You can decide that you want your relational model to look different, in which case you may bypass this problem altogether. It wouldn't be an answer to your question though.
Using internal EF voodoo
I've rather quickly looked around the reference documentation for DbContext, ObjectContext and ObjectStateManager, and I can't immediately find any way to change the type of an entity. If you have better luck than me, you may be able to use DTOs and DbPropertyValues to do your conversion.
Important note
With the first two workarounds, you'll likely hit a bunch of problems with navigational properties and foreign keys (because of the DELETE+INSERT operation). This would be a separate question.
Conclusion
EF is not that flexible when you do anything non-trivial, but it keeps improving. Hopefully this answer won't be relevant in the future. It's also possible that I'm not aware of an existing killer-feature that would make what you want possible, so don't make any decisions based on this answer.

Summary column on EF

Is it possible to add summary properties(no database column) according LINQ from another property(column) in EF generated class from database and this property don't update(delete or remove from class) when update model from database(because this property(cloumn) is not on database)
Yes, it is. Classed generated by Entity Framework as an Entitied are always marked partial. It lets you extend the functionality with your own properties or method.
Let say your entity class is named Post. You can extend it with code like that:
public partial class Post
{
public int Average
{
get
{
return this.Items.Average();
}
}
}
Because it's not a part of designer-generated file it won't be overwritten when it's regenerated. However, there is one requirement to make it work: your custom part of Post class has to be in exactly the same namespace as code generated by EF.
Try using the [NotMapped] attribute on a property in a partial class. This will be ignored by Entity Framework.
public partial class EntityName
{
[NotMapped]
public int CalculatedProperty
{
get
{
return Numbers.Sum();
}
}
}