Insert Derived class as Base Class [duplicate] - c#

I have created an entity data model and generated a database from it.
One of the entities is called Template.
Created partial classes to extend the functionality of Template works fine.
If I create a new class and try to derive from Template, I get a runtime exception upon instantiating:
Mapping and metadata information could not be found for EntityType 'Template001'.
How can I work around this? I definitely need to inherit from the EF classes.
EDIT
Does not seem possible. If that is the case, what would be the best way to implement the following requirement: The template entity stores information about templates that each have their own code to execute. That is why I was trying to derive from the entity in the first place.

It is not supported. You cannot derive a new type from entity and use it instead of the mapped entity type for persistence. If you want to have derived class from entity you must use mapped inheritance where every child is also mapped to the database.

Why do you need to inherit from entity class first of all? If you want to add some simple behavior, use partial class.
Update: Based on comments, it appears that there is possibility that behavior will be extended over the time. In this case, I would recommend using composition/aggregation, not inheritance. Let the classes that need to be extended have an entity as a field. In Raheel's scenario, it would be a class called TemplateLogic with field/property of type Template.

Related

Polymorphic cross-associations on Entity Framework

OK, this is an interesting and most importably real urgent problem for me to solve... In order for others to neatly comprehend it, I've stretched myself to make a well illustrated post.
The Object Model
So I have this simple, easy and "beautiful" model in mind. See the first picture. (You can ignore PathEntry, it's not relevant in my situation.)
The idea is that a MediaFeedItem owns:
a collection of ThumbnailFileEntries (accesible through the ThumbnailFiles property)
at most 1 raw FileEntry (MetadataFile property) and
at most 1 MediaFileEntry (MediaFile property)
We shall refer to these last three entity types as the file entities.
Now there's more: As you can see, I am inheriting both ThumbnailFileEntry and MediaFileEntry from FileEntry, and let's not debate that! (for now), it's one of those end-of-story aspects of the design and both entity types will continue to grow later on.
This already brings me some significant issues right away in regards to the polymorphic associations induced by the relationships from the file entities to MediaFeedItem.
The first thing that you shall observe is that I have eliminated the navigation property from the derived file entities (ThumbnailFileEntry and MediaFileEntry) to the primary entity MediaFeedItem.
I do this because they already inherit that property defined in the base class FileEntry. As you can see, I do not delete the roles at the end of these associations.
The Relational Model
I shall be using the so-vastly-conceptually-superior TPT strategy for generating and mapping my Object Model to the RDB world (vs TPH/TPC).
I'm using EF5-rc, the EDMX model designer to design my model, and the EF5 DbContext Generator to generate a DbContext and POCOs cuz I wanna use the DbContext API.
As you can see, I can nicely generate the database model using the EF tools:
The Problem
When loading a new MediaFeedItem and saving it, I get the following error:
System.InvalidOperationException: Multicplicity constraint violated. The role 'MetadataFile' of the relationship 'MediaFeedModel.MediaFeedItem_MetadataFile' has multiplicity 1 or 0..1.
What am I doing wrong?
Looking at your problem one thing stands out, The FK relationship between File and MediaFeedItem is required (IE a file must have a MediaFeedItem), but in the case where you are in an extended version of File you probably dont want this.
What i think you want to do is one of the following:
change the multiplicity on MediaFeedItem_FileEntry to 0..1 - 0..1 so that it isnt required at either end
create a new extended type to handle your metadataFile type and remove the direct reference between the base type and MediaFeedItem
I personally think the second is a more elegant solution to your problem as its creating an actual type for your MetadataFile
What appears to be happening is that you are trying to create an extended type but the base type isnt actually a metadata file.

WP7 Linq To SQL(SQL CE) IDataErrorInfo

What is the best practice for implementing IDataErrorInfo for an entity class. A class that is associated with a table or view.
I have a View that binds to a record from a Task entity class and need to validate the data before it is saved to the SQL CE database. Need to know the best way to implement IDataErrorInfo in this case. I assume just do it on the Task entity class, but want to make sure. Since I have many entity classes that will need validation.
Are you using autogenerated entities? In such case the usual practice is creating second file in the same project where entity is defined and create its second partial part:
public partial Task : IDataErrorInfo
{
...
}
The reason why the interface is implemented in another partial part is that the initial part is autogenerated by some API (Linq-to-sql, EF, etc) and that API can regenerate the code each time you do some changes. That regeneration would delete your changes but if you place them to your own partial part changes will not be deleted.

default vs custom using entity framework

I've got a table of default templates. It's global to all users. If a user has no custom template, I want to pull the default. If a user decides to customize the template it should be saved in a customtemplates table - as opposed to the globaltempaltes table.
the custom table has all the globaltemplates fields plus a userid and an id relating to which global it is replacing.
To flesh this out a bit more, lets say there are 3 templates, and a user wants to customize template 2 only. I would normaly pull the whole globaltemplates table and whatever relates to the user in the customtemplates table. Then, in the class property I'd do something in the get like this:
MyTemplateA
get { return customtemplates.A ?? globaltemplates.A; }
Can I do this using straight ef4/linq without poco?
Would a partial class with some additional properties like the get above work?
Since i'm always editing only the customtemplates table (add/edit/delete) it doesn't matter which version of the template I pull. I guess it could get hairy figuring out if it's an insert or an update.
In my opinion it will not work as you expect because EF closely relates entity to table. You cannot have single entity mapped to two tables except very special situations like splitting or inheritance.
So if you have Template entity it can be mapped only to single table but you have two. What you can do is to use TPC inheritance where Template will be a base entity mapped to GlobalTemplates table and UserTemplate will be derived entity mapped to UserTemplates table. TPC (table per concrete type) is type of inheritance where table for derived entity contains all columns from table for parent entity.
But inheritance still has a few problems for your scenario:
Template is editable - if you want to have it read only you must correctly handle it in your application logic. Any changes to attached Template instance will be saved when you call SaveChanges on the context.
When you load Template you cannot directly convert it to UserTemplate to make it user specific. You must create new instance of UserTemplate and copy properties from Template to the newly created instance.

Extending Entity Framework Model to include new property

I'm new to EF so please excuse me if this is a noob question.
Basically, we have a EF model set up using Model First for our 'platform' project and is shared across many applications which we build on top of this platform. In some of these applications we want to extend the classes to include additional properties without changing the model in the platform. Is this possible with EF 4 and how would I be able to do it without modifying the .edmx file?
I notice that the generated classes are all partial so potentially I could create a new partial class with the same name to include the new properties but is there any mappings that need to be taken care of?
p.s. under normal circumstances I'd have preferred to use inheritance and create a new class to hold the new properties instead but again, I don't know how to do that with EF.. any enlightenment here will be much appreciated!
Many thanks,
You cannot use inheritance because once entity is loaded from the data source EF will not know about inheritance and because of that it will instantiate base type without your properties instead of derived type with your properties. Any inheritance must be mapped in EDMX if EF have to work with it.
Using partial class will solve your problem but:
All parts of partial class must be defined in the same assembly
Properties from your partial part are not persisted to the database
Properties from your partial part cannot be used in linq-to-entities queries
EF generates partial classes. So to extend MyEntity, create a MyEntity.cs file with
partial class MyEntity
{
public string MyExtraProperty {get;set;}
}
edit: in the same namespace as your generated entities
I agree with adding additional properties to partial class of your entities (as you and Kaido said).
This way you can freely add the properties you want, without modifying generated classes and if you generate your model again (or update it from DB), your partial class is not modified.
In my opinion, adding properties to partial classes of generated entities is the way to go.

Fluent Nhibernate - Mapping two entities to same table

I'm trying to map two domain entities to the same table. We're doing a smart entity for our domain model, so we have the concept of an Editable Address and a readonly Address. I have both mapped using Classmaps, and everything seems to go fine until we try to export the schema using the SchemaExport class from NHibernate. It errors out saying the table already exists.
I assume it's something simple that I'm just not seeing.
Any ideas?
Thanks
Update
There are a couple of other things I didn't mention which I should have. I appreicate those that answered so far, but they don't work for us.
One is that we have a single address table, not include the columns in whatever entities have an address.
The other is that we can't use a common base class. For editable objects, we have a super class which adds validation behaviors to the subclasses. The readonly objects don't need this behavior though and should not have these behaviors.
I have considered an interface, but then I believe I end up in a situtation where you can cast a readonly object to this interface and then changes its values (since presumably NHibernate would use said interface to hydrate the object).
So if there's another way to acomplish this, or if mapping via an interface won't have the problem I described, please let me know. I'm still learning NHibernate.
Thanks again!
you can Exclude the readonly class from schemaexport:
public class ReadonlyAdressMap : ClassMap<ReadonlyAdress>
{
ReadonlyAdressMap()
{
Schemaaction.None();
[...]
}
}
Create one base abstract class entity which you will later extend to the Editable Address and the ReadOnly Address.

Categories

Resources