Repositories represents a single table in the database and provides an abstraction layer to handle datas. Every row in the database is an instance of a specific model type.
Therefor you need:
Every data model derives from BaseDataModel to enable seriaization and other internal data handling. Id and Name is coming from BaseDataModel.
Important is to override the Clone() method from base class. This Clone() method will be used on repository level to prevent changing in-memory cached datas.
⚠️ When no "Clone" method is existing, some errors like "The method or operation is not implemented." will be shown.
public class FriendshipDataModel : BaseDataModel { public override object Clone() { return this; } }
The repository needs to be derived from BaseDataRepository<> and IDataRepository<>.
Add the repository to the services.
services.AddSingleton<FriendshipRepository, FriendshipRepository>();
Minimum eg.:
public class FriendshipRepository : BaseDataRepository<FriendshipDataModel>, IDataRepository<FriendshipDataModel> { public FriendshipRepository(IConfiguration configuration, IServiceProvider serviceProvider) : base(configuration, serviceProvider) { base.TableName = "Friendships"; } public string GetCreateTableSql() { return @" CREATE TABLE Friendships ( Id UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(), UserAId UNIQUEIDENTIFIER NOT NULL, UserBId UNIQUEIDENTIFIER NOT NULL, State VARCHAR(MAX), );"; } }
This example will create the table with all fields.
The BaseDataRepository provides logic to execute sql queries, but the repository class must define the sql statement by itself.
Example methods for create, update:
public bool Create(FriendshipDataModel settingsDataModel) { var sql = @"INSERT INTO Friendships (Id, UserAId, UserBId, State) VALUES (@Id, @UserAId, @UserBId, @State)"; base.Create(sql, settingsDataModel); return true; } public bool CreateOrUpdate(FriendshipDataModel friendshipDataModel) { var existing = GetById(friendshipDataModel.Id); if (existing == null) { return Create(friendshipDataModel); } return Update(friendshipDataModel); } public bool Update(FriendshipDataModel friendshipDataModel) { var sql = @"UPDATE Friendships SET State = @State WHERE Id = @Id"; var parameters = new { Id = friendshipDataModel.Id, State = friendshipDataModel.State }; return base.Update(friendshipDataModel.Id, sql, parameters); }