I am using Entity Framework Database First for working with db.
I have a base class EntityBase
public class EntityBase
{
public Int32 Id { get; set; }
}
I have some other classes that are generated by EnitytFramework and represents tables of my db, for example, "User" class:
public class User
{
public int32 Id{get;set;}
public class Name{get;set;}
public class Age{get;set;}
}
I want all EF model classes to be inherited from EntityBase:
public class User : EntityBase
I can do this manually, by deleting Id field from User class and defining inheritance, but after I am updating model from db, all manually-made changes dissapears.
Is there any way to keep or automatically add inheritance to EF model classes?
EF database first work with t4 files if you change manually the class, save and compile, T4 will generate the classes again and you lose your changes.
You must make this change in T4 template. Search the EntityClassOpening method and change the last line:
_typeMapper.GetTypeName(entity.BaseType)
with this code:
_typeMapper.GetTypeName(entity.BaseType) ?? "EntityBaseClass"
Related
I have a ASP.NET MVC + EF web application, but I get an error when trying to query a list of Product using LINQ:
Invalid column name 'Discriminator'. Invalid column name 'NewProductPhoto'
This happened after I added a derived class from one of my entities.
My entity class:
[Table("Product")]
public partial class Product
{
public Product()
{
ProductPhotos = new HashSet<ProductPhoto>();
SalesOrderItems = new HashSet<SalesOrderItem>();
}
// more attributes here
}
My new derived class:
public class ProductEx : Product
{
public byte[] NewProductPhoto { get; set; }
}
I understand that EF tries to distinguish between Product and ProductEx but the point is I have no intention to add ProductEx to EF model.
I don't know why it considers ProductEx as part of database model.
How can I tell EF to not consider ProductEx as database model.
I found that the same way I can exclude a property from entity framework persistent, I can exclude my ProductEx class from entity framework modeling.
The attribute [NotMapped] does the trick.
[NotMapped]
public class ProductEx : Product
{
public byte[] NewProductPhoto { get; set; }
}
I still don't understand why EF even considers my derived class for persistence.
Sometimes when I update in the database, and go update the model from database EntityFramework classes gets deleted after update, I searched a lot for a solution but I found that I have to delete edmx file and create it again.
I do that and the problem solved but the code I wrote in the model classes removed like the validation code, is there anyway can I keep the code I wrote even I delete and recreate edmx file ?
EntityFramework will rebuild/generate all of the classes every time you change something.
If I got your problem right, I suggest using metadata classes:
public class EntityModel{
public int Test {get; set;}
}
public class EntityModel2{
public int Test2 {get; set;}
}
Then create 2 new files: Metadata.cs and PartialClasses.cs
Metadata.cs
public class Metadata{
public class EntityModelMetadata {
[JsonIgnore] //or whatever you need
public int Test {get; set;}
}
public class EntityModel2Metadata {
[XmlIgnore] //or whatever you need
public int Test2 {get; set;}
}
}
PartialClasses.cs
namespace YourNamespace{
[MetadataType(typeof(EntityModelMetadata))]
public partial class EntityModel {}
[MetadataType(typeof(EntityModel2Metadata))]
public partial class EntityModel2 {}
}
You need to create _Metadata class for each model you want to change and than you need to connect metadata class with EntityFramework class in PartialClasses.cs in the same way like shown.
In my solution I have two projects: SharePoint and Class Library. In ClassLibrary is a class DBContext and models. "Enable-Migration" generated class Configuration.cs. Next, I created the first migration through the "Add-Migration Initialize" and it worked. My next step was to "Update-Database" everything was fine. But after a while I changed the model and I wanted to generate migration. Unfortunately, I get a blank method Up and Down. Entity Framework does not see my changes ... The models are written without annotations and Context it inherits DbContext and is written like this:
public class SchoolContext: DbContext
{
public SchoolContext (): base () {}
public DbSet <Student> Students;
}
Models are written in this way:
public class Student
{
public int FirstName {get; set; }
}
I'm using EF5 to produce a model from an existing DB structure. I map Insert/Update/Delete Stored Procedures to the entities. This is working fine.
What I would like to do next is pass a UserId to these SPs as a parameter but not have the UserId as a column within the underlying table (the SPs will utilize this parameter). I have lots of entities. Is it possible to somehow add a property that will always be added back in even after updating the model from the DB?
Many Thanks
If you are using EDMX to generate the Entity Framework object model, your classes are partial and you can add properties to the partial classes of your entities which will survive database regeneration.
If you have a ParticularEntity table in the DB and referenced in the EDMX, you may add a partial class file ParticularEntity.Augments.cs (the name is for your reference, and you can have multiples as normal with partial classes) to your project and within it
public partial class ParticularEntity
{
public string UserId { get; set; }
public void DoSomething(string userId)
{
someFunctionThatYouWantToNotBeAnExtension();
}
}
Alternatively, you could write a set of extension methods which your maps utilize. I don't think that's as clean as extending the EF classes with partials, though.
Entity created by EF are partial class so you can extend that class with your custom properties
YourEntity.cs //created by EF
public partial class YourEntity
{
public string Name { get; set; }
...
}
YourEntityExtended.cs // created by you
public partial class YourEntity
{
public int Id { get; set; }
}
I have a DLL with a base model using code first EF 4.3.
What i want is to extend certain models in that dll with additional fields.
for example in BaseModel.DLL
namespace BaseModel
{
public class Account
{
public Id { get;set;}
public string Name {get;set;}
}
}
in a referencing project i want to extend the Account model (and DB table):
public class Account : BaseModel.Account
{
public string SomeAdditionalInfo { get;set;}
}
I want to end up with a table Account with fields
Id
Name
SomeAdditionalInfo
This way i can keep reusing the BaseModel (and logic) in several similar projects.
I guess i can't use partial classes because we're speaking different DLL's.
Maybe inheritance? I tried several ways but i keep getting conflicts about having 2 models with the same name.
Any hints? tips? solutions?
You can use inheritance though Table per Hierarchy.
You can create base class AccountBase and child class Account:AccountBase:
public class AccountBase
{
public Id { get;set;}
public string Name {get;set;}
}
public class Account : AccountBase
{
public string SomeAdditionalInfo { get;set;}
}
It generates Table AccountBase that will contains columns Id, Name, SomeAdditionalInfo
There will be also column Discriminator that will contains instance of what class contains in this row.