Ho un modello che viene utilizzato per gestire le relazioni di amicizia. Sembra come segue:
public class Relationship
{
[Required]
public User User { get; set; }
[Required]
public User Friend { get; set; }
[Required]
public DateTimeOffset RelationshipInitializationDate { get; set; }
}
Gli utenti avranno più record per il loro ID e ci saranno più record con lo stesso FriendID, quindi definire uno di questi come una chiave è un no-go. Vorrei che la chiave fosse un composto tra Utente e Amico ma quando la definisco in questo modo:
modelBuilder.Entity<Relationship>().HasKey(r => new { r.User, r.Friend });
Ottengo un errore che afferma:
The property 'Relationship.User' is of type 'User' which is not supported by current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Come dovrei andare su questo per creare la chiave primaria che collegherà con un oggetto utente e amico. Non ho avuto problemi con i miei altri oggetti con proprietà digitate e non ho alcun problema se aggiungo una chiave arbitraria al modello Relationship. Grazie in anticipo
L'idea di base qui è quella di aggiungere proprietà al modello che EF può usare per creare una relazione. Proprio tu stai cercando di creare una relazione di tipo User
e questo sta creando un errore. Per assegnare una chiave composta, ogni chiave deve essere un tipo compatibile con un campo Key
, non una proprietà di navigazione. Quindi aggiungiamo UserId
e FriendId
di tipo int
, string
o GUID
ecc. E creiamo una relazione su tali proprietà.
public class Relationship
{
public User Friend { get; set; }
public User User { get; set; }
public int FriendId { get; set; }
public int UserId { get; set; }
public DateTimeOffset RelationshipInitializationDate { get; set; }
}
public class User
{
public int UserId { get; set; }
}
È ora possibile definire una chiave composta su UserId
e FriendId
. Qualcosa come questo dovrebbe fare:
public class NorthwindContext : DbContext
{
public NorthwindContext(DbContextOptions<NorthwindContext> options):base(options) { }
public NorthwindContext() { }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Relationship>().HasKey(table => new {
table.FriendId, table.UserId
});
}
public DbSet<Relationship> Relationships { get; set; }
public DbSet<User> Users { get; set; }
}