using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Luticate2.Utils.DataAccess; using Luticate2.Utils.Dbo.Filter; using Luticate2.Utils.Dbo.Result; using Microsoft.EntityFrameworkCore; using WebApiWebSem.DataAccess.Models; using WebApiWebSem.Dbo.Articles; namespace WebApiWebSem.DataAccess { public class ArticlesDataAccess : LuEfCrudDataAccess { protected static IList Types = new List{"home", "persons", "locations", "countries"}; public ArticlesDataAccess(IServiceProvider serviceProvider) : base(serviceProvider) { } protected override object GetId(string id) { return id; } protected override IQueryable GetGetQueryable(WsDbContext db, IQueryable table) { return table.Include(articles => articles.articles_fields_fk); } protected override IQueryable GetEditQueryable(WsDbContext db, IQueryable table) { return GetGetQueryable(db, table); } protected override DbSet GetTable(WsDbContext db) { return db.articles; } protected string GetFilterType(LuFilterDbo filter) { var type = filter.GetFilterString("type", null); if (type == null || !Types.Contains(type.ToLower())) { return null; } return type.ToLower(); } protected override Expression> GetFilterExpression(LuFilterDbo filter) { var type = GetFilterType(filter); var q = string.IsNullOrEmpty(filter.Query) ? null : filter.Query; return articles => (type == null || articles.type == type) && (q == null || (WsDbContext.lu_texts_match(q, articles.text) || WsDbContext.lu_texts_match(q, articles.id))); } protected override articles GetModelFromTCreate(ArticlesAddDbo obj) { return new articles { id = obj.Id, picture_caption = obj.PictureCaption, picture_url = obj.PictureUrl, type = obj.Type, articles_fields_fk = obj.Fields.Select(dbo => new articles_fields { property = dbo.Property, type = dbo.Type, value = dbo.Value }).ToList(), text = obj.Text }; } protected override void EditModelFromTUpdate(ArticlesEditDbo obj, articles model) { model.picture_caption = obj.PictureCaption; model.picture_url = obj.PictureUrl; model.text = obj.Text; } protected override LuResult _EditSingleById(articles model, ArticlesEditDbo update, WsDbContext db, IQueryable table) { foreach (var removed in model.articles_fields_fk.Where(fields => update.Fields.FirstOrDefault(dbo => dbo.Property == fields.property) == null).ToList()) { model.articles_fields_fk.Remove(removed); } foreach (var field in model.articles_fields_fk) { var f = update.Fields.First(dbo => dbo.Property == field.property); field.value = f.Value; field.property = f.Property; field.type = f.Type; } foreach (var added in update.Fields.Where(dbo => model.articles_fields_fk.FirstOrDefault(fields => dbo.Property == fields.property) == null)) { model.articles_fields_fk.Add(new articles_fields { value = added.Value, property = added.Property, type = added.Type, article_id = model.id }); } return LuResult.Ok(true); } protected override ArticlesDbo GetDboFromModel(articles model) { return model.ToDbo(); } } }