C#C
C#5mo ago
Rodonies

EF Core mapping to Viewmodels without duplicating viewmodels

//EF Core Entities
DogEntity {
    public string Nickname;
    public List<DogOwnerRelationEntity> Relationships;
}

DogOwnerRelationEntity {
    public DogEntity Dog;
    public OwnerEntity Owner;
    public int RelationshipScore;
}

OwnerEntity {
    public string Name;
    public List<DogOwnerRelationEntity> Relationships;
}

//ViewModels
DogViewModel {
    public string Nickname;
    public List<DogOwnerRelationViewModel> Relationships;
}

DogOwnerRelationViewModel {
    public DogViewModel Dog;
    public OwnerViewModel Owner;
    public int RelationshipScore;
}

OwnerViewModel {
    public string Name;
    public string PhoneNumber;
    public List<DogOwnerRelationViewModel> Relationships;
}

//Extension methods
//this will end up running forever due to the circular nature of the many-to-many relationship, ignore this for now.
public static OwnerViewModel ToViewModel(this OwnerEntity ownerEntity) {
    return new {
        Name = ownerEntity.Name;
        Relationships = [.. ownerEntity.Relationships.Select(static relationship => relationship.ToModel()]
    }
}

public static DogOwnerRelationViewModel ToViewModel(this DogOwnerRelationEntity relationshipEntity) {
    return new {
        RelationshipScore = relationshipEntity.RelationshipScore;
        Dog = relationshipEntity.Dog.ToViewModel()
        Owner = relationshipEntity.Owner.ToViewModel()
    }
}

public static DogViewModel ToViewModel(this DogEntity dogEntity) {
    return new {
        Nickname = dogEntity.Nickname;
        Relationships = [.. ownerEntity.Relationships.Select(static relationship => relationship.ToModel()]
    }
}

List<DogEntity> DogEntities = GetDogsFromDatabase()
List<DogViewModel> DogViewModels = [.. DogEntities.Select(dogEntity => dogEntity.ToViewModel())];
Was this page helpful?