Я хотел бы знать, как лучше всего объединиться с ado.net, используя шаблон репозитория.
Пример:
public class PostRepository : BaseRepository<int, PostModel>
{
private static PostRepository instance;
public static PostRepository Instance
{
get
{
return instance ?? (instance = new PostRepository());
}
}
private PostRepository() : base("Post")
{
}
public override PostModel Convert(IDataRecord dataRecord)
{
return new PostModel()
{
Id = (int)dataRecord["Id"],
Body = dataRecord["Body"].ToString(),
Title = dataRecord["Title"].ToString(),
Date = (DateTime)dataRecord["Date"],
AuthorID = (int)dataRecord["AuthorID"],
CategorieId = (int)dataRecord["CategorieId"]
};
}
public override int Insert(PostModel entity)
{
Command command = new Command($"insert into {TableName} (Body,Title,Date,AuthorID,CategorieId) " +
$"output inserted.id " +
$"values(@Body,@Title,@Date,@AuthorID,@CategorieId)");
command.AddParameter("Body", entity.Body);
command.AddParameter("Title", entity.Title);
command.AddParameter("Date", entity.Date);
command.AddParameter("AuthorID", entity.AuthorID);
command.AddParameter("CategorieId", entity.CategorieId);
return (int)Connection.ExecuteScalar(command);
}
public IEnumerable<PostModel> GetByCategoryId(int id)
{
Command command = new Command($"select * from {TableName} where CategorieId = @id");
command.AddParameter("id", id);
return Connection.ExecuteReader(command, Convert);
}
Итак, я хотел бы присоединиться, но проблема в том, что данные, которые я получу, больше не будут объектами типа PostModel, так как мне это сделать?
Заранее спасибо!
Редактировать:
Вот мой класс BaseRepository
Я также создал набор инструментов для ADO, но я не думаю, что это было полезно, что я публикую его
public abstract class BaseRepository<TKey, TEntity> : IRepository<TKey, TEntity> where TEntity : IEntity<TKey>
{
private string tableName;
private Connection connection;
private string connectionString = "Server=DESKTOP-QTO99IS;Database=ForumYoutube;Trusted_Connection=True;";
protected Connection Connection
{
get { return connection; }
}
protected string TableName { get { return tableName; } }
public BaseRepository(string tableName)
{
this.tableName = $"[{tableName}]";
connection = new Connection(connectionString);
}
public TEntity Get(TKey id)
{
Command command = new Command($"select * from {tableName} where id = @id");
command.AddParameter("id", id);
return connection.ExecuteReader(command, Convert).SingleOrDefault();
}
public IEnumerable<TEntity> GetAll()
{
Command command = new Command($"select * from {tableName}");
return connection.ExecuteReader(command, Convert);
}
public bool Delete(TKey id)
{
Command command = new Command($"delete * from {tableName} where id = @id");
command.AddParameter("id", id);
return connection.ExecuteNonQuery(command) == 1;
}
public abstract TEntity Convert(IDataRecord dataRecord);
public abstract bool Update(TEntity entity);
public abstract TKey Insert(TEntity entity);
}