Saturday, 4 May 2024

Entity Framework Core : Configuring Entity properties, Primary Key in the DataModel.

 Include and exclude columns from entity: By convention all the public properties with Getter and Setter will be included in the Model. To Exclude any property we can apply [NotMapped] attribute.

public class Blog {

    public int BlogId { get; set; }

    public string Url { get; set; }

    [NotMapped]

    public DateTime LoadedFromDatabase { get; set; }

}

or

protected override void OnModelCreating(ModelBuilder modelBuilder) {

    modelBuilder.Entity<Blog>().Ignore(b => b.LoadedFromDatabase);

}

Column Names Mapping: By Convention Column name will be mapped to the property having same name. we can change this behavior by applying attribute or changing on OnModelCreating().

public class Blog {

    [Column("blog_id")]

   public int BlogId { get; set; }

    public string Url { get; set; }

} 

OR

protected override void OnModelCreating(ModelBuilder modelBuilder) {

    modelBuilder.Entity<Blog>()

                            .Property(b => b.BlogId)

                            .HasColumnName("blog_id");

}

We can also specify datatype of a column in Attribute or using fluent API 

[Column(TypeName = "varchar(200)")]

or using fluent API

eb.Property(b => b.Url).HasColumnType("varchar(200)"); (rest of the code would be similar to above onModelCreating.


Primary Key Configuration

By convention property named 'Id' or <TypeName>Id would be configured as primary key. explicitly we can declare any column as primary key by applying [Key] attribute or in OnModelCreating()

[Key]

public string LicensePlate { get; set; }

OR 

 modelBuilder.Entity<Car>().HasKey(c => c.LicensePlate);

We can also configure composite primary Key like:

modelBuilder.Entity<Car>().HasKey(c => {c.LicensePlate, c.Model} );


Foreign Key Shadow Property

Shadow properties are most often used for foreign key properties, where they are added to the model by convention when no foreign key property has been found by convention or configured explicitly.


No comments:

Post a Comment

How to create and use middleware in asp.net core

Middleware is piece of code that's assembled into an app pipeline to handle requests and responses.  Each middleware component in the re...