How to implement custom features in a model on . NET?

Asked

Viewed 113 times

4

I needed to implement some features in the model users but as you can see early on this class is automatically generated by Entity, so whenever I upgrade or recreate the model the custom functionalities will be lost.

Example of a custom implementation done on the model users:

public string full_name
{
    get
    {
        return this.first_name + ' ' + this.last_name;
    }
}

Is there a way to overwrite the model to maintain these custom features without overwriting them every time I upgrade / recreate the model?

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace E_Learning.Models
{
    using System;
    using System.Collections.Generic;
    using E_Learning.Helpers;

    public partial class users
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public users()
        {
            this.updated_at = DateTime.Now;
            this.created_at = DateTime.Now;

            this.signatures = new HashSet<signatures>();
            this.testimonials = new HashSet<testimonials>();
        }

        public int id { get; set; }
        public string identity_ { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string email { get; set; }
        public string telephone { get; set; }
        public string password { get; set; }
        public Nullable<System.DateTime> birthday { get; set; }
        public Nullable<int> sexuality { get; set; }
        public string remember_token { get; set; }
        public System.DateTime updated_at { get; set; }
        public System.DateTime created_at { get; set; }
        public Nullable<byte> status { get; set; }
        public string handle { get; set; }

        public string setHandle ()
        {
            return Slugify.Make(this.first_name + ' ' + this.last_name);
        }

        public string full_name
        {
            get
            {
                return this.first_name + ' ' + this.last_name;
            }
        }

        private Nullable<int> age
        {
            get
            {
                DateTime now = DateTime.Today;

                if (this.birthday.HasValue)
                {
                    DateTime birthday = DateTime.Parse(this.birthday.ToString());
                    int age = now.Year - birthday.Year;

                    if (now < birthday.AddYears(age))
                        age--;

                    return age;
                }

                return null;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<signatures> signatures { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<testimonials> testimonials { get; set; }
    }
}

Print:

inserir a descrição da imagem aqui

3 answers

4

One of the principles of object-oriented programming, SOLID, is that an object should be closed for maintenance, but open for extension.

To add functionality to a closed object for maintenance, simply extend it. See:

public static class UserExtensions
{
    public static string FullName(this User user) =>        
         $"{user.first_name} {user.last_name}";
}

And then just consume:

var usuario = new User { first_name = "Thiago", last_name = "Lunardi" };
Console.WriteLine( usuario.FullName() ); // Thiago Lunardi

See working here.

See more in this article about SOLID - OCP - Open/Closed Principles.

4


This has been more or less answered in How to edit a Partial Class?

Partial classes exist precisely for this type of problem. You create the customizations in a separate file that will be compiled together.

Of course you cannot touch anything in the generated file. This will always be lost when updating the model. You have to find an organization and even create design patterns to decouple one part of the other if you have some more complex things to do (in most cases just have simple methods).

Then create another file with class partial Users and do whatever you need there. Note that the class has already been generated with this intention.

You cannot override an existing property. What you can do is create another one that calls the original created by EF. Only the EF property will be persisted, yours will be auxiliary. It may not be ideal, but as far as I know there is no other way. In your example, it will work perfectly, FullName is a great complementary property to FirstName and LastName.

Depending on what you do you can add add-ons to the generated model in a metadata class. It doesn’t seem to be what you want, but it is an alternative in some cases.

In the future you may have the supersedes or something like that. I believe it’s tailor-made for this problem. Then you can say in the partial class that one property should replace the other generated in the other part of the class, more or less as if it were a virtual method (of course the mechanism is much simpler and solved all in compilation).

An example is the use of events: Partial for separation of events and methods. Example with WPF: Centralize (use only one) a Try-catch for every WPF application. Example with ASP.NET: Error adding While value to List<>

Can help: Create partial (partial) method in C#

Another solution is to adopt the Model First that puts an end to this problem and is the future of the RU, the present in the EF Core.

4

  • Good use of classes partial. However, the Pattern ViewModel does not have that end. In this reply I talk about the ideal use of it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.