4

I am developing a .Net application and I have Database available. I have a category class like :

public partial class Category
{
   public int CategoryId {get;set;}
   public string CategoryName {get;set;}
}

How can I add dynamic fields to this model and hence to the database? if not possible then is there any other way to fulfill my problem?

I am allowing the user to add his desired custom fields to be added. So, my database schema becomes

Category(CategoryId, CategoryName, CustomField1, CustomField2);

How can I do this using EF 5 and MVC ? Or is there any other way we can do it ?

5
  • 1
    Can you give more details behind why you would want to dynamically add these CustomFields? I'm thinking there may be a better way to accomplish this than adding database fields on the fly like this. Commented Mar 27, 2014 at 13:33
  • You would need to basically recompile at runtime (somehow) the entire managed module which loaded the EF model after adding the fields. It might be possible but is entirely not practical. Commented Mar 27, 2014 at 13:38
  • 2
    I would suggest adding a list to your Category class, which is like a list of objects called CustomField and just add more to that list. So in your DB you would have a CustomFields table relating to Category Commented Mar 27, 2014 at 13:49
  • It is not right approach (idea in question) Commented Mar 27, 2014 at 13:50
  • I want to provide the functionality to user to add some custom field like as vTiger (vtiger.com) application. i have shown that some CRM tools provide user to add custom field on the fly to database and display on the add/edit and list page. Eg. we have a product module and in the module we have just provide below field 1. Product Name 2. Product Type 3. Product Price Now user want to add another filed in product module as per it's requirement like 1. Product Category 2. Product Description Commented Nov 28, 2018 at 11:02

1 Answer 1

5

Going to add this suggestion as an answer, as I don't think dynamically adding columns to the database is the best idea.

In your Category class, add in a list of another type, lets call it CustomField. When you allow a user to add a new field, just stick it in this list

public partial class Category
{
   public int CategoryId {get;set;}
   public string CategoryName {get;set;}
   public IList<CustomField> CustomFields {get;set;}
}

public class CustomField
{
   public int CustomFieldId {get;set;}

   public string FieldName {get;set;}
   public string FieldValue {get;set;}

   [ForeignKey("Category")]
   public int CategoryId {get;set;}
   public Category Category {get;set;}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.