CollaboratingPlatypus / PetaPoco

Official PetaPoco, A tiny ORM-ish thing for your POCO's
Other
2.07k stars 600 forks source link

Setting the TableNameAttribute in Constructor #383

Closed bhattjidotcom closed 7 years ago

bhattjidotcom commented 7 years ago

I am using PetaPOCO with DotNetNuke Modules.

As you are aware, DNN passes a parameter objectQualifier . i.e. we need to prefix that parameter at runtime, to the tablename

Currently I have to pass the tablename parameter, every time I use any Insert, Update or Delete method. However, it would be great, if we can set the TableNameAttribute in constructor itself, so that there are no chance of error at all

QuAzI commented 7 years ago

Looks like it is dbprefix in other CMS. As example "oc_" for OpenCart. This feaure is required because without it we must write any time crazy queries like

SELECT {dbprefix}product.product_id, {dbprefix}product.sku FROM {dbprefix}product 
INNER JOIN {dbprefix}product_to_category ON {dbprefix}product_to_category.product_id = {dbprefix}product.product_id
WHERE {dbprefix}product_to_category.category_id = {category_id};

and use string.Replace() to fill all fields instead use ORM. Also table can exist or have different fields depending on the version. At best variant need 1) some exceptions safe fabric which can use 'DESCRIBE {dbprefix}table' to fill structure from DB. 2) read-only fields to read generated tableName and fields names 3) dictionary-like filling (with skipping missed fields) Something like it

// create table instance
var tableInstance = db.TableFromDescribe("{dbprefix}table");

// Some tables available depending on the version too
if (tableInstance.Exist())
{
    // precalculated fields
    var values = new Dictionary<string, string>
    {    
        { "id", product.IdShopDb },
        { "name", product.Name },
        { "summary", product.SmallDescription },
        { "meta_title", product.MetaTitle },
        { "meta_keywords", product.MetaKeywords },
        { "meta_description", product.MetaDescription },
        { "description", product.FullDescription },
        { "contact_id", "1"}
    };

    // heavy calculation on demand
    if (tableInstance.HasField('sku_count'))
    {
        values["sku_count"] = skuCountGenerateHeavyFuncion();
    }

    var rec = tableInstance.CreateItemInstance();

    // update
    rec.FillFromDictionary(values);

    // or create
    rec = tableInstance.CreateItemFromDictionary(values);

    // Update data in DB
    db.Save(rec);
}