Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / Javascript
Tip/Trick

How to Implement ObjectStatus with EntityWorker.Core and JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
8 Jul 2018CPOL 12.3K   5   3
How to implement ObjectStatus with EntityWorker.Core and JavaScript

Introduction

Using EntityWorker.Core to save and delete object depending on objectstatus.

Background

How many web developers use JavaScript to modify items, then save it to the database?

Here, I'm going to show you a way to modify objects, then save it to the database with ease.

Using the Code

Modules

First let's start with creating our modules.

We will create a Page class that contains many categories as an example.

C#
public enum ObjectStatus = { Added, Removed }
public abstract class Entity{
  [PrimaryKey]
  public Guid? Id { get; set; }
  public ObjectStatus Object_Status { get; set; }
 }

 public class Category: Entity {
 public string Name { get; set; }
 }

 public class PageCategory: Entity {
  [ForeignKey(typeof(Page)]
  public Guid Page_Id { get; set;}
  [ForeignKey(typeof(Category)]
  public Guid Category_Id { get; set; }
  [IndependedData] // so only PageCategory should be removed and not Category
  public Category Category { get; set; }
 }

 public class Page: Entity {
  [ToBase64String]
  [AllowHtml]
  public string Content { get; set; }
  // this is what we are interested of
  // this list will contains values that should be added/updated or removed from the database
  public List<PageCategory> Categories { get; set; }
 }

Now that we have our Modules, we should prepare our dbContext and override the save mechanism of entityworker.core.

C#
using EntityWorker.Core.Interface;
using EntityWorker.Core.Transaction;
using System;
using System.Collections;
using System.Linq;

    public class DbContext : Transaction
    {
        public DbContext() : base(GetConnectionString(), EntityWorker.Core.Helper.DataBaseTypes.Mssql)
        {

        }     
        // here we have overridden the same and added functionality of object status
        public override IRepository Save(object entity)
        {
            void Prepare(object data)
            {
                if (data == null)
                    return;
                var props = EntityWorker.Core.FastDeepCloner.DeepCloner.GetFastDeepClonerProperties
                                         (data.GetType()).Where(x => !x.IsInternalType && x.CanRead);
                foreach (var prop in props)
                {
                   if  (prop.ContainAttribute<JsonDocument>() ||
                        prop.ContainAttribute<XmlDocument>() ||
                        prop.ContainAttribute<ExcludeFromAbstract>()) // Ignore 
                        continue;
                    var value = prop.GetValue(data);
                    if (value == null)
                        continue;
                    if (value is IList)
                    {
                        IList newList = (IList)Activator.CreateInstance(value.GetType());
                        var ilist = value as IList;
                        var i = ilist.Count - 1;
                        while (i >= 0)
                        {
                            var e = ilist[i] as Entity;
                            i--;
                            if (e.Object_Status == EnumHelper.ObjectStatus.Removed)
                            {
                                Delete(e);
                            }
                            else newList.Add(e);
                        }
                        prop.SetValue(data, newList);

                    }
                    else
                    {
                        var e = value as Entity;
                        if (e.Object_Status == EnumHelper.ObjectStatus.Removed)
                        {
                            Delete(e);
                            prop.SetValue(data, null);
                        }
                        else Prepare(e);
                    }
                }
            }

            if (entity as Entity != null)
            {
                if ((entity as Entity).Object_Status != EnumHelper.ObjectStatus.Removed)
                    Prepare(entity);
                else
                {
                    Delete(entity);
                    return this;
                }
            }
            return base.Save(entity);
        }

        protected override void OnModuleStart()
        {
            if (!base.DataBaseExist())
                base.CreateDataBase();

            // You could choose to use this to apply you changes to the database or create your 
            // own migration
            // that will update the database, like alter drop or create.
            // Limited support for sqlite
            // Get the latest change between the code and the database. 
            // Property Rename is not supported. renaming property x will end up removing the x and 
            // adding y so there will be dataloss
            // Adding a primary key is not supported either
            var latestChanges = GetCodeLatestChanges();
            if (latestChanges.Any())
                latestChanges.Execute(true);

            // Start the migration
            InitializeMigration();
        }

        // get the full connection string
        public static string GetConnectionString()
        {
            return @"Server=.\SQLEXPRESS; Database=SEO; User Id=root; Password=root;";
        }
    }
}

Now we prepare a json data that contains an object to be added/updated or removed.

C#
// this is our test category
var category = new dbContext().Get<Category>().Json(); 
var pagesJson = { 
content: "test",
categories: [
{ id:"5ac53e44-ba94-4a76-b94f-032077c1ef10", category: category } // this should be updated
{ category: category }, /// this will be added 
{ id:"5ac53e44-ba94-4a76-b94f-032077c1ef79", category: category, 
  object_status: "Removed" } // dbContext should now remove this data
]            
}  

And now the only thing left is to save this json to the database:

C#
using (var db = new DbContext()){
var page = db.FromJson<Page>(pagesJson); // or use your own JsonConvert
db.Save(page);
db.SaveChanges();
}

Points of Interest

This is really helpful when you are developing web application and using JavaScript(Json) to manipulate the data.

I hope that you learn from this.

History

  • 14th May, 2017: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sweden Sweden
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseThanks Pin
Member 1386766911-Jun-18 1:18
Member 1386766911-Jun-18 1:18 
QuestionWhat is ObjectStatus and its objective Pin
Mou_kol10-Jun-18 23:16
Mou_kol10-Jun-18 23:16 
AnswerRe: What is ObjectStatus and its objective Pin
Alen Toma13-Jun-18 6:36
Alen Toma13-Jun-18 6:36 
its a way to dynamicly edit, add and delete objects. this make using javascript to edit,add and delete items much easer

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.