Ho creato una semplice applicazione ASP di Entity Framework che funziona ma non so perché:
Ho creato un contesto come questo:
public class AstootContext : DbContext
{
public AstootContext(DbContextOptions<AstootContext> options)
: base(options)
{ }
public DbSet<Account> Accounts { get; set; }
public DbSet<User> Users { get; set; }
}
E ho due tavoli con modelli come questo:
public class Account
{
public int Id { get; set; }
public string Username { get; set; }
public string PasswordHash { get; set; }
public DateTime Created { get; set; }
List<User> Users { get; set; }
}
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DateTime Birthday { get; set; }
public Account Account { get; set; }
}
La cosa interessante è che quando eseguo la mia applicazione in realtà è in grado di raccogliere i dati. Sembra strano perché non ho specificato alcuna mappatura delle tabelle. Sto assumendo questo solo automaps perché le tabelle specificate hanno lo stesso nome.
Le mie domande sono:
Come faccio a specificare il mapping della tabella esplicita della tabella nel caso in cui non desiderassi che i nomi dei miei modelli corrispondessero esattamente al DB?
Come faccio a specificare il Mapping colonna personalizzato.
C'è qualcosa di speciale che devo specificare per chiavi primarie / esterne
modificare
Chiarire
dire che avevo una tabella in DB MyAccounts e volevo mapparla ad un account di entità.
Dire che avevo una password di colonna e volevo che mappasse su una proprietà POCO PasswordHash
Per specificare il nome della tabella del database, puoi utilizzare un attributo o l'API fluente:
Usando gli attributi:
[Table("MyAccountsTable")]
public class Account
{
public string PasswordHash { get; set; }
}
Utilizzo dell'API Fluent:
public class YourContext : DbContext
{
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Language>(entity => {
entity.ToTable("MyAccountsTable");
});
}
}
Per denominare manualmente le colonne, è molto simile e puoi utilizzare un attributo o l'API fluente:
Usando gli attributi:
public class Account
{
[Column("MyPasswordHashColumn")]
public string PasswordHash { get; set; }
}
Utilizzo dell'API Fluent:
public class YourContext : DbContext
{
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Language>(x => x
.ToTable("MyAccountsTable")
.Property(entity => entity.PasswordHash)
.HasField("MyPasswordHashColumn")
);
}
}