Why the frequent unexplained use of the partial modifier in EF Code First? - entity-framework

In the EF Code first docs and examples, you'll frequently see classes and methods defined using the partial modifier. For example, the following
public partial class Department
{
public int DepartmentID { get; set; }
public DepartmentNames Name { get; set; }
public decimal Budget { get; set; }
}
I understand the general use of the partial keyword by the C# compiler. However, I often see these examples without applying that functionality (i.e., the class is never re-opened elsewhere).
In other examples, I have also seen partial modifiers on methods as well.
Do these modifiers carry some special meaning in an EF Code First context? Can anyone help me understand what's going on?

Given EF makes working with POCOs really easy, this makes it flexible in terms of separating components and pieces. For example, a section that defines your models:
public partial class PurchaseOrder
{
public Int32 ID { get; set; }
public String CustomerName { get; set; }
public Double InvoiceAmount { get; set; }
public virtual ICollection<PurchaseOrderItem> Items { get; set; }
}
Then apply business logic elsewhere:
public partial class PurchaseOrder : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// ...
}
}
And maybe extend its functionality another place still:
public partial class PurchaseOrder
{
public void AddItem(PurchaseOrderItem item)
{
// ...
}
}
though as #E.J. Brennan mentions, it's more likely they were generated from a T4 template. This means that anything you did in the generated file would be wiped with every generation; however, if you left the generated item alone, you could still extend it (like I've shown with IValidatableObject or additional methods) without worrying if your changes would be lost.

It wouldn't be unusual to use T4, or another code generator to create the basic classes that map back to your database. If one did that, you would want those classes to be partial so that you could extend those classes in a seperate file - if you extended those classes in the original file, they would get overwritten every time you re-generated the file.
If you hand coded your classes, there would be no need to use the partial on all of them.

You can extend Entity Framework generated types:
The classes only contain properties that are defined in the conceptual model and do not contain any methods. The generated classes are partial.
So, in your new partial classes (not the generated ones) you can define business logic, display attributes, validation logic etc. These classes won't be overwritten, like the generated ones.

Related

Entity Framework 6 load derived class of entity

In Entity Framework 6, given class A and derived class B: A, I would like to load entities A into instances of B without having to code for each property.
So given:
public class A
{
public Guid AId { get; set; }
public string Value { get; set; }
}
public class B: A
{
[NotMapped]
public string OtherValue { get; set; }
}
public MyDbContext: DbContext
{
public DbSet<A> As { get; set; }
}
I would like to:
using (MyDbContext db = new MyDbContext())
{
IEnumerable<B> Bs = db.As.LoadBsSomehow()
}
I'm guessing I could add DbSet<B> Bs { get; set; } and then in OnModelCreate I could override the table name to As perhaps. I'd like to avoid that if I can.
The purpose of doing this is that we need view models that need the underlying model plus some other properties and I don't want to mess up the models with all the different view model properties. This would simplify coding and maintenance for when the main model is changed -- the inheritance would automatically handle the changes in the derived class (view models).
I can then set the additional properties of the Bs in a Select or other method.
Also, I do NOT want to use reflection. I can code that up if I need it. I'd rather find out if EF 6 has the ability to do this natively.
UPDATE: I can do DbContext.Database.SqlQuery<T>. I would prefer to be able to use LINQ instead of writing SQL. I have no problem writing SQL, but LINQ is much more maintainable from a code perspective. Perhaps if I can use LINQ to create an IQueryable<B> and get the SQL for it?

Mapping custom collection's property to column in EF

I'd like this class:
public class InvertedList<T> : List<T>{
public bool IsInverted { get; set; }
}
when used in the entity like this:
public class Parent {
public InvertedList<Child> Children { get; set; }
}
to map into database tables like
CREATE TABLE Parent (
Child_IsInverted bit
);
CREATE TABLE Child (
ParentId int
)
I've tried putting [Column] on the IsInverted property, [ComplexType] on InvertedList class, but the property is always ignored.
Is there any way to do something like this or anything similar?
Of course I can do it manually like
public class Parent {
public bool Child_IsInverted { get; set; }
public List<Child> Children { get; set; }
}
But I really don't like to put all those Child_IsInverted properties (I'll have quite a lot of such invertable lists) on Parent entity. The only way I can think of to at least partially implement this would be to have separate domain and db models, and transform it using the repository - this way I could work using desirable model, but it looks like a little bit too much effort for such a task. Can you offer any other options?
When EF deserialize a List<> (everything implementing ICollection<>) it does not serialize other properties than the content.
Just a suggestion, Compex types that could be an option does not support generics and does not support navigation properties and you here have both.

ef5 database first data annotation

I am starting MVC4 with VS2012. I am also using EF5 with the "Database First" method of creating my classes.
However because the generated glasses can be regenerated I cannot put the Data Annotation details to assist with validation.
I have seen some code snippets that use MetaData and partial classes but I was wondering if anyone knows of a small compilable example that I can look at and pull apart to better understand how the vasious classes interlink.
Many many thanks for any help.
Dave
You can achieve what you need through extending models. Suppose that EF generated the following entity class for you:
namespace YourSolution
{
using System;
using System.Collections.Generic;
public partial class News
{
public int ID { get; set; }
public string Title { get; set; }
public int UserID { get; set; }
public virtual UserProfile User{ get; set; }
}
}
and you want do some work arounds to preserve your you data annotations and attributes. So, follow these steps:
First, add two classes some where (wherever you want, but it's better to be in Models) like the following:
namespace YourSolution
{
[MetadataType(typeof(NewsAttribs))]
public partial class News
{
// leave it empty.
}
public class NewsAttribs
{
// Your attribs will come here.
}
}
then add what properties and attributes you want to the second class - NewsAttribs here. :
public class NewsAttrib
{
[Display(Name = "News title")]
[Required(ErrorMessage = "Please enter the news title.")]
public string Title { get; set; }
// and other properties you want...
}
Notes:
1) The namespace of the generated entity class and your classes must be the same - here YourSolution.
2) your first class must be partial and its name must be the same as EF generated class.
Go through this and your attribs never been lost again ...

Code first TPC Inheritance with concrete base and derived, concrete types in EF

I'm trying to set up a TPC inheritance using Code First to model incoming and outgoing messages and the records therein.
The base type, SentRecord, is concrete and its derived type, ReceivedRecord, is also concrete and inherits from SentRecord and adds a few extra fields in order to record return codes. Something like this, but with more properties:
public class SentRecord : RecordBase {
public int Id { get; set; }
public string FooField { get; set; }
}
public class ReceivedRecord : SentRecord {
public int ReturnCode { get; set; }
public SentRecord SentRecord { get; set; }
}
The current model is TPH and as a result the tables get a descriminator column to identify the type of object that was persisted. It works, but I'd prefer both objects to be stored in separate tables, without the need of the discriminator column. The table SentRecord would only have the columns Id and FooField and the table ReceivedRecord would have Id, FooField, ReturnCode and an FK to SentRecord.
I currently have the following in my DataContext class:
public class Context : DContext {
public DbSet<SentRecord> SentRecords { get; set; }
public DbSet<ReceivedRecord> ReceivedRecords { get; set; }
}
And I have the following configuration for the ReceivedRecord:
public class ReceivedRecord_Configuration : EntityTypeConfiguration<ReceivedRecord>{
public ReceivedRecord_Configuration() {
this.Map(m => {
m.MapInheritedProperties();
m.ToTable("ReceivedRecords");
});
}
}
And the following for SentRecord:
public class SentRecord_Configuration : EntityTypeConfiguration<SentRecord>{
public SentRecord_Configuration() {
this.Map(m => {
m.MapInheritedProperties(); //In order to map the properties declared in RecordBase
m.ToTable("SentRecords");
});
}
}
But once I run this, I get the following error when EF is trying to initialize my database:
Problem in mapping fragments starting at lines 455, 1284:
An entity from one EntitySet is mapped to a row that is also mapped to an entity from another EntitySet with possibly different key.
Ensure these two mapping fragments do not map two unrelated EntitySets to two overlapping groups of rows.
I'm not sure what to do in order to set this up in the TPC way I described above? Or should I stick with TPH which works?
Thanks in advance!
Okay, I got it up and running. Truth be told, the example I gave was a little bit less complex than the actual classes and inheritance hierarchy I was working with. That hierarchy contained a lot of abstract classes and concrete classes from which other classes inherited.
'Flattening' the hierarchy by getting cutting down on inheritance made it work smooth and without any errors whatsoever. Response messages aren't inherited from the sent messages anymore.
Short version: Don't make complex inheritance trees with mixed concrete and abstract base types when trying to use code-first database models. It'll only make it more complex to persist.

Entity Framework - DataAnnotations

Using MVC3 and Entity Framework.
Am trying to get validation flowing from data model
Question: On an entity framework save, how can I automatically put in the [MetadataType tag below for my buddy class?
[EdmEntityTypeAttribute(NamespaceName="ModelValidationTestModel", Name="Person")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
[MetadataType(typeof(Person_Validation))] // I want EF to put this line in automatically
public partial class Person : EntityObject
...
[Bind(Exclude="PersonID")]
public class Person_Validation
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Email { get; set; }
}
Using example from: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
I think the best option is not to mess with the class generated by EF. Instead define your own partial class:
[MetadataType(typeof(Person_Validation))]
public partial class Person
{
//rest of class may be empty
}
You can do this in the same file as the Person_Validation class if you like.
It's not automatic, but it is safe (your changes won't get lost). This approach will work with any code generation framework (that uses partial classes), not just EF.
Data Annotations/attributes are baked at compile time and you cannot add them dynamically. I would recommend you to avoid passing/getting your EF models to/from the views. You should be using view models which are classes specifically tailored to the needs of a given view. It is those view models that will handle the would handle view specific validations such required, format, ...). You could then use AutoMapper to have your controller map between your view models and the EF models.