question

codexennial avatar image
0 Votes"
codexennial asked ZhiLv-MSFT commented

Adding Custom Fields to User Entity

I am using this tutorial to add a couple fields to the user table. In my code I have the following lines:

 protected override void OnModelCreating(ModelBuilder builder)
 {
     base.OnModelCreating(builder);
    
     builder.Entity<ApplicationUser>()
         .Property(e => e.RegistrationDate);
    
     builder.Entity<ApplicationUser>()
         .Property(e => e.RegistrationIPAddress);
    
     builder.Entity<ApplicationUser>()
         .Property(e => e.Banned);
 }

I have looked up lambda expression which I believe is what this is, but I'm not understanding what these lines do, and why they are required, i.e.:

  1. What is the point of the RegistrationDate line and what is it doing?

  2. Do I need to add these lines for every new field I add to the user table?

This is my first time working with Entity Framework and all of the documents are getting a little confusing.

Thanks.


dotnet-csharpdotnet-aspnet-core-generaldotnet-entity-framework-coredotnet-entity-framework
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
1 Vote"
karenpayneoregon answered karenpayneoregon commented

For ASP.NET, see the following [Identity model customization in ASP.NET Core][1].

In general, for EF Core, builder.Entity<ApplicationUser>().Property(e => e.RegistrationDate); is describing a table property using a builder pattern.

Some other examples

Tell EF Core that a column named ModifiedDate has a default value for new records.

 entity.Property(e => e.ModifiedDate).HasDefaultValueSql("(getdate())");

Describing relations between two tables.

 entity.HasOne(d => d.ContactTypeIdentifierNavigation)
     .WithMany(p => p.Customers)
     .HasForeignKey(d => d.ContactTypeIdentifier)
     .HasConstraintName("FK_Customers_ContactType");

For more indepth information see [Creating and configuring a model][2]

In a complex model it's prudent to break out each table configuration as shown below in the attached image.

![129536-ef-config.png][3]

Do I need to add these lines for every new field I add to the user table?

Yes


[1]: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-5.0
[2]: https://docs.microsoft.com/en-us/ef/core/modeling/
[3]: /answers/storage/attachments/129536-ef-config.png

ef-config.png (14.1 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

It seems like this code first approach is overly complicated. I'm having issues understanding several things. Is it still acceptable to do things the "old" way by creating the database manually using SQL Management Studio and connecting an ASP.Net Core Web application via ADO (or another method)? It seemed less complicated as I was able to design the database via the SQL Management Studio designer rather than attempting to design it using code. Setting up all the relationships, indexes, FK/PK via code is very complicated.

If so, do you have any up-to-date tutorials on how to do it this way? Everything I find now is code first.

0 Votes 0 ·

My advise is to create the database and tables in SSMS then use EF Power Tools to reverse engineer the database or part of the database. You then really only need to be concerned with the connection string as it will be hard coded but you can a) use appsetting.json and set the connection string there or set an environment variable and dynamically use one appsettings for test, one for dev, one for prod.


0 Votes 0 ·
ZhiLv-MSFT avatar image
2 Votes"
ZhiLv-MSFT answered ZhiLv-MSFT commented

Hi @codexennial,

What is the point of the RegistrationDate line and what is it doing?

Entity Framework Core uses a set of conventions to build a model based on the shape of your entity classes. we can specify additional configuration to supplement and/or override what was discovered by convention via the Data annotations or Fluent API.

By using the above lambda expression in the OnModelCreating method, it is the Fluent API method to configure the class and its properties. In the lambda expression, for example, we can call the relate method to configure the relationship between tables or configure the property is required.

You can refer the following sample:

 internal class MyContext : DbContext
 {
     public DbSet<Blog> Blogs { get; set; }

     #region Required
     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         modelBuilder.Entity<Blog>()
             .Property(b => b.Url)
             .IsRequired(); 
     }
     #endregion
 }

 public class Blog
 {
     public int BlogId { get; set; }
     public string Url { get; set; }
 } 

By using the above code, we can use the IsRequired method to make the url is required when insert new entity. You can also use the data annotations to configure a model, code like this:

 using System.ComponentModel.DataAnnotations;
 using Microsoft.EntityFrameworkCore;
    
 namespace EFModeling.DataAnnotations.Required
 {
     internal class MyContext : DbContext
     {
         public DbSet<Blog> Blogs { get; set; }
     }
    
     #region Required
     public class Blog
     {
         public int BlogId { get; set; }
    
         [Required]
         public string Url { get; set; }
     }
     #endregion
 }

In this scenario, we can see that there is no need to add the lambda expression in the OnModelCreating method.

Do I need to add these lines for every new field I add to the user table?

No, if you want to specify additional configuration to supplement and/or override what was discovered by convention, you can add the lambda expression in the OnModelCreating method. Otherwise, there is no need to use them.

More detail information, you can refer the following articles:

Creating and configuring a model

Fluent API in Entity Framework Core

Besides, to learn EF Core with Asp.net Core, I suggest you could refer the following tutorials:

Entity Framework Core

OverView of Entity Framework Core

EF Core With MVC


If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Best regards,
Dillion

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for the reply.

IIf I'm understanding correctly, the lines in this project are basically doing nothing the way they are written, and can be safely deleted? This is because it's not actually setting any additional configuration...

      builder.Entity<ApplicationUser>()
          .Property(e => e.RegistrationDate);

Edit: Reading the replies again. I'm not sure I understood correctly.

0 Votes 0 ·

Hi @codexennial,

    builder.Entity<ApplicationUser>()
        .Property(e => e.RegistrationDate);

Yes, you are right, the above code doesn't set any additional configuration. So, you can safely delete them. You can also create a new sample to verify it.

1 Vote 1 ·