Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding ToString, Equals,.. in Entities when using Entity Framework

I would like to override ToString, Equals and GetHashCode methods of an Entity generated by the model of the Entity Framework.

What could be the best way of doing this?

Now I'm manually editing the ___Model.Designer.cs file that generates the model, but everytime I change the model, of course, I lost these changes.

like image 696
Oscar Mederos Avatar asked Apr 15 '11 06:04

Oscar Mederos


People also ask

What happen if we override toString () method?

Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.

Is toString always override?

So just because a data class defines a toString doesn't mean you shouldn't override it.

Why is it needed to override toString () method in a DTO class?

Overriding toString to be able to print out the object in a readable way when it is later read from the file.


1 Answers

Every Entity is defined as a partial class, so that you can define an additional partial class to extend the Entity with additional properties or methods.

Lets say you have defined an Entity Person in your EntityModel.

Now you can create a new class file name Person.cs in your project. Within the class file you define a

public partial class Person{
   // Here you can add your additional functionality or method overrides
}

The partial class must be defined in the same namespace and the same assembly as the Person Entity.

The new class file is unaffected by changes in the EntityModel (Only if you remove the Entity or change properties, then your partial class might need an update).

like image 97
Jehof Avatar answered Sep 20 '22 05:09

Jehof