Use NotMapped Attribute to exclude Property from being in Entity
public class EntityName { [NotMapped] private string PropertyName { get; } }
Daily Notes of a Programmer
public class EntityName { [NotMapped] private string PropertyName { get; } }
var context = new BiContext(); var entityType = context.Model.FindEntityType(typeof(InvoiceDetail)); var tableName = entityType.GetTableName(); Console.WriteLine(tableName); var properties = entityType.GetProperties(); # Property Name in Class foreach (var p in properties) { Console.WriteLine(p.Name); } # Column Name in Table foreach (var p in properties) { Console.WriteLine(p.GetColumnName()); }
[Index(nameof(Url))] public class Blog { public int BlogId { get; set; } public string Url { get; set; } }
Composite index
[Index(nameof(FirstName), nameof(LastName))] public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
Index uniqueness
[Index(nameof(Url), IsUnique = true)] public class Blog { public int BlogId { get; set; } public string Url { get; set; } }
Index sort order
[Index(nameof(Url), nameof(Rating), AllDescending = true)] public class Blog { public int BlogId { get; set; } public string Url { get; set; } public int Rating { get; set; } }
[Index(nameof(Url), nameof(Rating), IsDescending = new[] { false, true })] public class Blog { public int BlogId { get; set; } public string Url { get; set; } public int Rating { get; set; } }
Index name
[Index(nameof(Url), Name = "Index_Url")] public class Blog { public int BlogId { get; set; } public string Url { get; set; } }
References
https://learn.microsoft.com/en-us/ef/core/modeling/indexes?tabs=data-annotations
var position = 20; var nextPage = context.Posts .OrderBy(b => b.PostId) .Skip(position) .Take(10) .ToList();
References
https://docs.microsoft.com/en-us/ef/core/querying/pagination
appsettings.Development.json
{ "DetailedErrors": true, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning", "Microsoft.Hosting.Lifetime": "Information", "Microsoft.EntityFrameworkCore.Database.Command": "Information" } } }
Database access
using var context = new MyContext(); return await context.MyEntities.ToListAsync();
if (Loading) { return; } try { Loading = true; ... } finally { Loading = false; }
New DbContext instances
builder.Services.AddDbContextFactory<ContactContext>(opt => opt.UseSqlite($"Data Source={nameof(ContactContext.ContactsDb)}.db"));
private async Task DeleteContactAsync() { using var context = DbFactory.CreateDbContext(); Filters.Loading = true; if (Wrapper is not null && context.Contacts is not null) { var contact = await context.Contacts .FirstAsync(c => c.Id == Wrapper.DeleteRequestId); if (contact is not null) { context.Contacts?.Remove(contact); await context.SaveChangesAsync(); } } Filters.Loading = false; await ReloadAsync(); }
Scope to the component lifetime
@implements IDisposable @inject IDbContextFactory<ContactContext> DbFactory
public void Dispose() { Context?.Dispose(); }
protected override async Task OnInitializedAsync() { Busy = true; try { Context = DbFactory.CreateDbContext(); if (Context is not null && Context.Contacts is not null) { var contact = await Context.Contacts.SingleOrDefaultAsync(c => c.Id == ContactId); if (contact is not null) { Contact = contact; } } } finally { Busy = false; } await base.OnInitializedAsync(); }
References
https://docs.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-6.0
dotnet ef dbcontext scaffold "Host=my_host;Database=my_db;Username=my_user;Password=my_pw" Npgsql.EntityFrameworkCore.PostgreSQL
If you have other tables in your database, you may use additional parameters – -Schemas and -Tables – to filter the list of schemas and/or tables that are added to the model. For example, you can use the following command:
dotnet ef dbcontext scaffold "host=server;database=test;user id=postgres;" Devart.Data.PostgreSql.Entity.EFCore -Tables dept,emp
References
https://www.npgsql.org/efcore/index.html
https://www.devart.com/dotconnect/postgresql/docs/EFCore-Database-First-NET-Core.html
Table name
[Table("blogs")] public class Blog { public int BlogId { get; set; } public string Url { get; set; } }
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .ToTable("blogs"); }
Table schema
[Table("blogs", Schema = "blogging")] public class Blog { public int BlogId { get; set; } public string Url { get; set; } }
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .ToTable("blogs", schema: "blogging"); }
Rather than specifying the schema for each table, you can also define the default schema at the model level with the fluent API:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema("blogging"); }
Column name
public class Account { [Column("MyPasswordHashColumn")] public string PasswordHash { get; set; } }
public class YourContext : DbContext { protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<Language>(x => x .ToTable("MyAccountsTable") .Property(entity => entity.PasswordHash) .HasColumnName("MyPasswordHashColumn") ); } }
References
https://docs.microsoft.com/en-us/ef/core/modeling/entity-types?tabs=data-annotations
https://stackoverflow.com/questions/42190909/how-to-specify-entity-framework-core-table-mapping
Remove all files from the migrations folder.
dotnet-ef database drop -f -v dotnet-ef migrations add Initial dotnet-ef database update
Do that only if you don’t care about your current persisted data
Without Dropping Database
The Issue: You have mucked up your migrations and you would like to reset it without deleting your existing tables.
The Problem: You can’t reset migrations with existing tables in the database as EF wants to create the tables from scratch.
What to do:
dotnet-ef migrations add Initial
. This will create a migration in your Migration folder that includes creating the tables (but it will not run it so it will not error out.)dotnet-ef database update
. It will apply the Migration (while not actually changing the database) and create a snapshot row in MigrationHistory.You have now reset your migrations and may continue with normal migrations.
References
https://stackoverflow.com/questions/11679385/reset-entity-framework-migrations
modelBuilder.Entity<Department>().Property(t => t.Name).IsRequired();
Configuring a Primary Key
modelBuilder.Entity<OfficeAssignment>().HasKey(t => t.InstructorID);
Configuring a Composite Primary Key
modelBuilder.Entity<Department>().HasKey(t => new { t.DepartmentID, t.Name });