Michał Poterek
Michał Poterek

Reputation: 33

C# generic type with obligatory property

I'm building a universal CRUD for MongoDB handling and I'm having trouble with generic type . Issue is that I need to use a property of the type but generic type doesn't have this by default.

public static Task UpdateConfig<T>(T config)
{
    IMongoCollection<T> collection = ConnectToMongo<T>("collectionName", "dataBase");
    FilterDefinition<T>? filter = Builders<T>.Filter.Eq("Id", config.Id);
    return collection.ReplaceOneAsync(filter, config, new ReplaceOptions { IsUpsert = true });
}

Problem lies in the line:

FilterDefinition<T>? filter = Builders<T>.Filter.Eq("Id", config.Id);

The config doesn't come with Id property but it is essential that this property is used. Can anyone help out with this?

Upvotes: 0

Views: 1242

Answers (2)

Morten Bork
Morten Bork

Reputation: 1632

Pseudo code here:

public interface IId {
   public int Id {get;set;}
}

public static Task UpdateConfig<T>(T config) where T : IId
    {
        IMongoCollection<T> collection = ConnectToMongo<T>("collectionName", "dataBase");
        FilterDefinition<T>? filter = Builders<T>.Filter.Eq("Id", config.Id);
        return collection.ReplaceOneAsync(filter, config, new ReplaceOptions { IsUpsert = true });
    }

This should work ish? Unless I totally screwed up the where syntax...

Upvotes: 0

Zohar Peled
Zohar Peled

Reputation: 82504

The way to handle requirements like this in dot net is to use generic constraints and an interface:

public interface IConfig // You might want to change this name
{
   int Id {get;} // data type assumed to be int, can be anything you need of course
}

....

public static Task UpdateConfig<T>(T config) where T : IConfig
... rest of the code here

Upvotes: 4

Related Questions