Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Implement ObjectStatus with EntityWorker.Core and JavaScript

0.00/5 (No votes)
8 Jul 2018 1  
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.

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.

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.

// 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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here