public interface IDataRepository<TEntity, U> where TEntity : class
{
IEnumerable<TEntity> GetAll();
TEntity GetFirstOrDefault(
Expression<Func<TEntity, bool>> filter = null,
string includeProperties = null
);
TEntity Get(U id);
long Add(TEntity b);
long Update(U id, TEntity b);
long Delete(U id); // Polachan
void Remove(int id); // Polachan
void Remove(TEntity entity); // Polachan
}
I have implimented Get, , Remove but I dont know how to implement GetAll, Update,Delete . How can I implement Delete , Update, SelectAll mathod in Repository class.
Repository.cs given below
public class DataRepository<TEntity,U> : IDataRepository<TEntity, U> where TEntity : class
{
protected readonly GoContext Context;
internal DbSet<TEntity> dbSet;
public DataRepository(GoContext context)
{
Context = context;
this.dbSet = context.Set<TEntity>();
}
public long Add(TEntity b)
{
dbSet.Add(b);
long id= Context.SaveChanges();
return id;
}
public TEntity Get(U id)
{
return dbSet.Find(id);
}
public TEntity GetFirstOrDefault(Expression<Func<TEntity, bool>> filter = null, string includeProperties = null)
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
//include properties will be comma seperated
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
return query.FirstOrDefault();
}
public void Remove(int id)
{
TEntity entityToRemove = dbSet.Find(id);
Remove(entityToRemove);
}
public void Remove(TEntity entity)
{
dbSet.Remove(entity);
}
public long Update(U id, TEntity b)
{
throw new NotImplementedException();
}
}
I myself, I use the DAO pattern with the DTO pattern, leaving the EF entities at the data access layer and just took the repository pattern out of the picture as a data persistence pattern. The EF entities are never used at the UI. And the DAO pattern just
keeps thing simple, becuase a DAO object is used on a per table bases.
You could use the POCO pattern instead of the DTO pattern.
I can do any thing I want in a DAO, becuase it's not generic and it's made for low level data accesses and persistence, the mapping.
An example....
using System.Collections.Generic;
using System.Threading.Tasks;
using Entities;
namespace DAL
{
public interface IDaoArticle
{
Task<List<DtoArticle>> GetAll();
Task<List<DtoArticle>> GetArticlesByAuthorId(int id);
Task<DtoArticle> Find(int id);
Task Add(DtoArticle dto);
Task Update(DtoArticle dto);
Task Delete(int id);
}
}
====================================================================
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL.Models;
using Entities;
using Microsoft.EntityFrameworkCore;
namespace DAL
{
public class DaoArticle :IDaoArticle
{
private PublishingCompanyContext pc;
private IDaoAuthor _daoAuthor;
public DaoArticle(PublishingCompanyContext dbcontext, IDaoAuthor daoAuthor)
{
pc = dbcontext;
_daoAuthor = daoAuthor;
}
public async Task<List<DtoArticle>> GetAll()
{
var dtos = new List<DtoArticle>();
var articles = await pc.Article.ToListAsync();
dtos.AddRange(articles.Select(article => new DtoArticle()
{
ArticleId = article.ArticleId,
AuthorId = article.AuthorId,
Title = article.Title,
Body = article.Body
}).ToList());
return dtos;
}
public async Task<List<DtoArticle>> GetArticlesByAuthorId(int id)
{
var dtos = new List<DtoArticle>();
var articles = await pc.Article.Where(a => a.AuthorId.ToString().Contains(id.ToString())).ToListAsync();
foreach (var article in articles)
{
var intid = (int)article.AuthorId;
var dtoauthor = await _daoAuthor.Find(intid);
var dto = new DtoArticle
{
ArticleId = article.ArticleId,
AuthorId = article.AuthorId,
AuthorName = dtoauthor.LastName +", " + dtoauthor.FirstName,
Title = article.Title,
Body = article.Body
};
dtos.Add(dto);
}
return dtos;
}
public async Task<DtoArticle> Find(int id)
{
var dto = new DtoArticle();
var article = await pc.Article.FindAsync(id);
if (article != null)
{
dto.ArticleId = article.ArticleId;
dto.AuthorId = article.AuthorId;
dto.Title = article.Title;
dto.Body = article.Body;
}
else
{
throw new Exception($"Article with ID = {id} was not found.");
}
return dto;
}
public async Task Add(DtoArticle dto)
{
var article = new Article
{
AuthorId = dto.AuthorId,
Title = dto.Title,
Body = dto.Body
};
pc.Article.Add(article);
await pc.SaveChangesAsync();
}
public async Task Update(DtoArticle dto)
{
var article = new Article
{
ArticleId = dto.ArticleId,
AuthorId = dto.AuthorId,
Title = dto.Title,
Body = dto.Body
};
pc.Entry(article).State = EntityState.Modified;
await pc.SaveChangesAsync();
}
public async Task Delete(int id)
{
var article = pc.Article.Find(id);
if (article != null)
{
pc.Article.Remove(article);
await pc.SaveChangesAsync();
}
}
}
}
Here the DAO(s) are used in a WebAPI that are established at StartUp.cs
using DAL.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DAL;
using System.Net;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Serilog;
namespace WebAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//DAL
services.AddTransient<IDaoAuthor, DaoAuthor>();
services.AddTransient<IDaoPayroll, DaoPayroll>();
services.AddTransient<IDaoArticle, DaoArticle>();
services.AddDbContext<PublishingCompanyContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
// Add framework services.
services.AddMvc(options =>
{
options.Filters.Add(new ErrorHandlingFilter(Configuration));
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory, IApplicationLifetime appLifetime)
{
//this is used by Postmon and Global Exception handelling to show exception.
app.UseExceptionHandler(
options =>
{
options.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var err = $"<h1>Error: {ex.Error.Message} </h1>{ex.Error.StackTrace } {ex.Error.InnerException.Message} ";
await context.Response.WriteAsync(err).ConfigureAwait(false);
}
});
}
);
loggerfactory.AddSerilog();
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
If you find the post has answered your issue, then please mark post as 'answered'.
What's the logic of you `Delete` method?Actually,your `Remove` method does the delete operation.
Here is a simple workaround like below:
1.Model:
public class GoUserDepotLink
{
[Key]
public int id { get; set; }
public int UserID { get; set; }
public int DepotID { get; set; }
public long DepotNo { get; set; }
}
2.DataRepository<TEntity, U>:
public void Remove(int id)
{
TEntity entityToRemove = dbSet.Find(id);
Remove(entityToRemove);
}
public void Remove(TEntity entity)
{
dbSet.Remove(entity);
Context.SaveChanges();
}
public long Update(U id, TEntity b)
{
dbSet.Update(b);
var value = Context.SaveChanges();
return value;
}
public IEnumerable<TEntity> GetAll()
{
var data = dbSet.ToList();
return data;
}
3.Controller:
public class GoUserDepotLinksController : Controller
{
private readonly GoContext _context;
private readonly IDataRepository<GoUserDepotLink, long> _t;
public GoUserDepotLinksController(GoContext context,
IDataRepository<GoUserDepotLink, long> t)
{
_context = context;
_t = t;
}
// GET: GoUserDepotLinks
public async Task<IActionResult> Index()
{
var model = new GoUserDepotLink()
{
id=1,
UserID=1,
DepotID=1,
DepotNo=1005
};
var data = _t.Update(1, model); //update the model's value with id = 1
var getall = _t.GetAll();//get all data
_t.Remove(1);//delte the record in database with id=1
return View();
}
}
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Member
400 Points
1295 Posts
How can I implement GetAll(), Delete(),Update() repository from Generic Repository into reposit...
Nov 04, 2019 08:21 AM|polachan|LINK
This s my basic datarepository
I have implimented Get, , Remove but I dont know how to implement GetAll, Update,Delete . How can I implement Delete , Update, SelectAll mathod in Repository class.
Repository.cs given below
Contributor
4873 Points
4124 Posts
Re: How can I implement GetAll(), Delete(),Update() repository from Generic Repository into rep...
Nov 04, 2019 02:53 PM|DA924|LINK
The repository pattern is not a data persistence pattern.
Maybe the data mapper pattern will help you with repositroy pattern using UoW.
http://www.bradoncode.com/blog/2013/08/repository-vs-domain-model-vs-data.html
I myself, I use the DAO pattern with the DTO pattern, leaving the EF entities at the data access layer and just took the repository pattern out of the picture as a data persistence pattern. The EF entities are never used at the UI. And the DAO pattern just keeps thing simple, becuase a DAO object is used on a per table bases.
You could use the POCO pattern instead of the DTO pattern.
https://blog.sapiensworks.com/post/2012/11/01/Repository-vs-DAO.aspx
https://www.tutorialspoint.com/design_pattern/composite_entity_pattern.htm
https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp
https://enterprisecraftsmanship.com/posts/dto-vs-value-object-vs-poco/
I can do any thing I want in a DAO, becuase it's not generic and it's made for low level data accesses and persistence, the mapping.
An example....
Here the DAO(s) are used in a WebAPI that are established at StartUp.cs
Contributor
2680 Points
874 Posts
Re: How can I implement GetAll(), Delete(),Update() repository from Generic Repository into rep...
Nov 05, 2019 07:25 AM|Rena Ni|LINK
Hi polachan,
What's the logic of you `Delete` method?Actually,your `Remove` method does the delete operation.
Here is a simple workaround like below:
1.Model:
2.DataRepository<TEntity, U>:
3.Controller:
4.Startup.cs:
Best Regards,
Rena