Core
Core
CC#
Created by Core on 6/3/2024 in #help
How to block the execution of a method when running EF migration
Hello, I have a background service registered in Program.cs. It does an HTTP call to an external service that is essential for getting some configuration settings. This HTTP call should not happen when ef commands are executed, so I was wondering what solutions might be there.
24 replies
CC#
Created by Core on 5/22/2024 in #help
Isolation level for reading a row only once
No description
4 replies
CC#
Created by Core on 5/16/2024 in #help
How to structure interfaces and their implementations
Hi, Which project structure is more common? Or is there any other used in practice? 1
ClassLib/
|
|-- Interfaces
| |- IOrder
| | -IPayment
|
|-- Implementations
| |- Order
| |- Payment
ClassLib/
|
|-- Interfaces
| |- IOrder
| | -IPayment
|
|-- Implementations
| |- Order
| |- Payment
2.
ClassLib/
|
|-- Orders
| |- IOrder
| |- Order
|
|-- Payments
| |- IPayment
| |- Payment
ClassLib/
|
|-- Orders
| |- IOrder
| |- Order
|
|-- Payments
| |- IPayment
| |- Payment
7 replies
CC#
Created by Core on 5/16/2024 in #help
✅ How to create a folder in project root?
No description
9 replies
CC#
Created by Core on 5/15/2024 in #help
Microservices - confusion about the structure
Hi, In a microservice architecture each service has its own deployment. But since the communication between the services happens with RabbitMQ, where does the deployment of that belong? Should I create a new repository just for RabbitMQ deployment, as all other services depend on it?
4 replies
CC#
Created by Core on 5/13/2024 in #help
UUID v4 vs v7
Hi, I had a model which primary key was type of long and it was used as cursor for pagination. This way I could simply do the following LINQ query: query.Where(l => l.Id >= queryParams.Cursor). I switched from long to Guid and I think this is no longer a good solution. Guid.NewGuid() generates a v4 UUID which is totally random. Surprisingly my query still works, and entities are in order, but that must be just a coincidence. What if I used v7 UUIDs? Since it is time based, would the cursor pagination function correctly?
8 replies
CC#
Created by Core on 5/7/2024 in #help
✅ EF multicolumn index by only having navigational property in the model
Hi, I am trying to create a multicolumn index and a foreign key would be part of it. With the help of the navigation property I am able to specify the foreign key, but I am unable to create the index. The syntax of the HasIndex is wrong, explicit string value cannot be used.
c#
public class Dog
{
public Guid Id {get; set; }
public string Alias {get; set; }

public Owner Owner { get; set; } // navigation property
}
c#
public class Dog
{
public Guid Id {get; set; }
public string Alias {get; set; }

public Owner Owner { get; set; } // navigation property
}
c#
private static void Configure(EntityTypeBuilder<Dog> builder)
{
builder.HasOne(b => b.Owner)
.WithMany()
.HasForeignKey("OwnerId");

builder.HasIndex(b => new { "OwnerId", b.Alias }) // Can't do this, but this is what I want to achieve
.IsUnique();
}
c#
private static void Configure(EntityTypeBuilder<Dog> builder)
{
builder.HasOne(b => b.Owner)
.WithMany()
.HasForeignKey("OwnerId");

builder.HasIndex(b => new { "OwnerId", b.Alias }) // Can't do this, but this is what I want to achieve
.IsUnique();
}
3 replies
CC#
Created by Core on 4/4/2024 in #help
.NET EF - How to generate a new database in runtime (dynamically)?
Hello, I have the following logic, a user can create multiple projects via an API call. For each project I would need to create a new database from a migration, so each project would have different database. How is this achievable?
23 replies
CC#
Created by Core on 3/30/2024 in #help
Are there other options for storing keys other than Azure Key Vault?
Hello, Azure Key Vault is the best option for storing RSA keys, but even I cannot access the private RSA key with the SDK. I need to sign JWTs, which are done regularly, by using the sign API exposed by the vault. This would be costly, as JWTs are signed regularly. Current scenario: 1. Generate 2 RSA keys: A and B 2. B is stored in Azure Vault and is only used to encrypt key A 3. The encrypted A key should be stored in a safer place than the database (because the private part of the key is needed too) Are there slightly better than the database for storing this RSA key?
14 replies
CC#
Created by Core on 3/29/2024 in #help
Azure Key Vault SDK has no method for exposing private RSA keys
Hello, I sign JWTs with a RSA private key and use the public key to validate them. The problem is that I am unable to sign the tokens, since Azure Vault does not expose the private RSA key. The tokens are being used for authentication, it is necessary to use RSA algorithm. Am I missing something? How should I proceed, as I feel like this is a dead end. 😭 Any help is highly appreciated!
4 replies
CC#
Created by Core on 3/7/2024 in #help
Can different validation attributed be applied to a field based on the active profile?
Hello, In Development I would need to apply a different validation attribute to a DTO field, without impacting performance. For example, having an extra if statement in the validation that checks the current profile and applies different validation is not the greatest idea . Gemini gave vague solution, like this:
c#
#if DEBUG
// Code specific to development environment (e.g., relaxed validation)
#else
// Code specific to production environment (e.g., stricter validation)
#endif
c#
#if DEBUG
// Code specific to development environment (e.g., relaxed validation)
#else
// Code specific to production environment (e.g., stricter validation)
#endif
Can the following be done?
c#
#if DEVELOPMENT
[DevelopmentIsValidHostnameFormat]
#else
[IsValidHostnameFormat]
#endif

public string? Hostname{ get; set; }
c#
#if DEVELOPMENT
[DevelopmentIsValidHostnameFormat]
#else
[IsValidHostnameFormat]
#endif

public string? Hostname{ get; set; }
17 replies
CC#
Created by Core on 3/5/2024 in #help
DTO validation with DRY principle (without repeating the same validation)
Hello, I would like to know what is used in practice, regarding the DTO validation. Let's say for 2 endpoints I would have nearly the same DTO, so the same properties would have the exact same annotations. As a result, code duplication would occur, and I would end up copying the lines back and forth. Is this what happens in practice?
3 replies
CC#
Created by Core on 1/6/2024 in #help
✅ EF - How to extract LINQ Select into a method does not work
I am trying to only include only the needed columns from a table with EF, by using Select. The following class is given:
c#
public class Animal
{
public int Id { get; set; }
public string? Name { get; set; }
}
c#
public class Animal
{
public int Id { get; set; }
public string? Name { get; set; }
}
Having a DbSet<Animal> Animals, I can do the following to select only the Id:
c#
_dbContext.Animals.Select(a => new Animal {Id = a.Id})
c#
_dbContext.Animals.Select(a => new Animal {Id = a.Id})
This works perfectly, but If I extract the object creation into a method, then the generated SQL query will still select all columns.
c#
_dbContext.Animals.Select(a => SelectOnlyNeeded(a))

private Animal SelectOnlyNeeded(Animal a) {
return new Animal {Id = a.Id};
}
c#
_dbContext.Animals.Select(a => SelectOnlyNeeded(a))

private Animal SelectOnlyNeeded(Animal a) {
return new Animal {Id = a.Id};
}
I am using TPC Inheritance and need to repeat some Select on individual Tables, that's why I am trying to extract the logic from Select. That way I would avoid repetition (DRY) I even tried a static class for creating the object, but it did not work.
c#
private static Animal SelectOnlyNeeded(this Animal a) {
return new Animal {Id = a.Id};
}
c#
private static Animal SelectOnlyNeeded(this Animal a) {
return new Animal {Id = a.Id};
}
Given the outcome, I am left with the impression that it is not possible what I am trying to do, but it would be great if someone proved me wrong.
17 replies
CC#
Created by Core on 1/5/2024 in #help
EF Core TPC Inheritance strategy - Select query to include individual navigational property
Hello, I have 2 similar entities, which are derived from a base class. The base class is Animal, while Cat and Dog are concrete types. Two tables are created for the concrete types. In addition Dog also has a navigational property, called Owner.
c#
public abstract class Animal
{
public int Id { get; set; }
public string? Name { get; set; }
}
public class Cat : Animal
{

}
public class Dog : Animal
{
public Owner Owner { get; set; }
}
c#
public abstract class Animal
{
public int Id { get; set; }
public string? Name { get; set; }
}
public class Cat : Animal
{

}
public class Dog : Animal
{
public Owner Owner { get; set; }
}
If a DbSet<Animal> Animals is defined, then both tables can be queried at the same time, by running _dbContext.Animals.ToList() (this will do a UNION ALL in the background). The problem is that this way the navigational property Owner for Dog type is not included, since _dbContext.Animals does not have Owner property. I could make it work the following way:
c#
_dbContext.Animals.Include(a => (a as Dog).Owner)
c#
_dbContext.Animals.Include(a => (a as Dog).Owner)
This works, but I don't think this is the right way to do it, since Cat is part of the queried entities too, and I also get a warning Dereference of a possibly null reference. I think it will try to map each type to Dog and a Cat mapped to Dog will be null. How could I specify to include the navigational property related to Dog entities?
3 replies
CC#
Created by Core on 12/31/2023 in #help
Is there a standard option to generate UUID version 7? (Guid)
Hello, .NET provides a way to generate UUID v4 with Guid.NewGuid(), but this cannot be used as a PK for tables. In Postgres newer UUID versions can be used as primary keys, as they are sortable and because of that there is no index fragmentation. Is there a standard library that is used for generating UUID 7? It is a bit odd there is no built in way to do this.
10 replies
CC#
Created by Core on 12/20/2023 in #help
✅ Extra query for user or attach it to the context?
Hello! A Web API uses a JWT for authentication. Is it better to query the user based on the claim extracted from the token or just attach it to the database context, assuming the user already exists? That would save an extra query and if the user did not exist EF would throw an exception. Is this suitable, or is it better to query the user?
7 replies
CC#
Created by Core on 12/8/2023 in #help
2 way cursor pagination design
Hi! If you were to implement a two-way cursor pagination with next_cursor and prev_cursor for an API endpoint, how would you handle the case when both cursors were provided in the request? 1. Error message 2. Prioritize one of the 2 cursors
6 replies
CC#
Created by Core on 12/6/2023 in #help
EF navigation property is unattached from dbContext
Hello! There are 2 Entities in relation with each other: User and Domain. When I want to insert a new Domain to the database an exception will occur, because the User related to it is not tracked. There are 2 solutions, but I cannot decide which one is better. 1. Do an extra query to get the User: domain.User = userRepo.FindUser(userId) 2. Write an extra class that attaches the user to the context: extraClass.AttachToDbContext(new User(userId)) - no extra query performed (User already exists in the database) I like the 2nd option better, but would like to hear other opinions
c#
public class User
{
public string UserId { get; set; }
}

public class Domain
{
public Guid DomainId { get; set; }
public string DomainName { get; set; }

public User User { get; set; }
}
c#
public class User
{
public string UserId { get; set; }
}

public class Domain
{
public Guid DomainId { get; set; }
public string DomainName { get; set; }

public User User { get; set; }
}
9 replies
CC#
Created by Core on 12/3/2023 in #help
EF Database is not seeded
Hello! I have configured an Entity and the table needs to have an initial row. After creating the migration and updating the database the row is still not there. Any ideas what might be missing? DbContext
c#
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
c#
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
Entity
c#
public void Configure(EntityTypeBuilder<Domain> builder)
{
builder.HasKey(d => d.DomainId);

builder.HasOne(d => d.User)
.WithMany()
.HasForeignKey(d => d.UserId)
.IsRequired(false);

builder.HasIndex(d => d.DomainName)
.IsUnique();

var sharedDefaultDomainName = new Domain
{
DomainId = Guid.NewGuid(),
UserId = null,
DomainName = "localhost:7151",
};

builder.HasData(sharedDefaultDomainName); //Here
}
c#
public void Configure(EntityTypeBuilder<Domain> builder)
{
builder.HasKey(d => d.DomainId);

builder.HasOne(d => d.User)
.WithMany()
.HasForeignKey(d => d.UserId)
.IsRequired(false);

builder.HasIndex(d => d.DomainName)
.IsUnique();

var sharedDefaultDomainName = new Domain
{
DomainId = Guid.NewGuid(),
UserId = null,
DomainName = "localhost:7151",
};

builder.HasData(sharedDefaultDomainName); //Here
}
21 replies
CC#
Created by Core on 12/1/2023 in #help
Database Design
Generic question. I cannot figure out how to design the database in the following scenario:
| Users |
-------
| Id PK |

and

| OtherTable |
------------
| Id PK |
| UserId FK |
| Value INT |
| Users |
-------
| Id PK |

and

| OtherTable |
------------
| Id PK |
| UserId FK |
| Value INT |
OtherTable is in relation with Users, but there is a default Value that should belong to all users. This can be solved by creating a resource with the same value for each user, but I feel like this is a bad practice. What other options do I have? I am using EF with Postgres, but I do not think that matters.
3 replies