How to add a new record to database?

Topics: Core, General
Nov 18, 2011 at 9:57 AM

Hello!

I'm trying to add data to database

ex: _orchardServices.ContentManager.New<SubPositionPart>("SubPosition");

But this doesn't work.What is incorrect?

But this works: _orchardServices.ContentManager.New<UserPart>("User");

Thanks!

Nov 18, 2011 at 10:31 AM

Have you created a Content Type called "SubPosition"?

Nov 19, 2011 at 4:05 AM

I want to add data from files to ten tables in the database.Can I do this without ContentManager?Because the data are not relating to content type.

 I know that I can to add with IRepository something this:

private readonly IRepository<UserRecord> _repository;
 
 public HomeController(IRepository<UserRecord> repository)
{
    _repository = repository;
}

 

But I have differently ten tables.How I can to do with IRepository without adding every tables IRepository to constructor?

 

Coordinator
Nov 19, 2011 at 6:01 AM

Well, ten is not that bad, but you could alternatively get them from the work context.

Nov 19, 2011 at 6:19 AM
bertrandleroy wrote:

Well, ten is not that bad, but you could alternatively get them from the work context.

How I can alternatively get them from the work context?Can you give some links or examples?

Thanks!

Coordinator
Nov 19, 2011 at 6:25 AM

You inject an IWorkContextAccessor, GetContext from it, and then you do a Resolve<T> for each repository you need.

Nov 19, 2011 at 6:46 AM

var subPositions = _workContextAccessor.GetContext().Resolve<SubPositionRecord>();
subPositions.Code = "Code";
subPositions.Name = "Name";

Now how I can to save this(subPositions) into the database?

 

Nov 19, 2011 at 11:45 AM

No, you need to get the IRepository<T> from the workcontext. The IRepository has the Create method which allows you to save the record.

The advantage of doing it like that is you only resolve the ones you need for any given operation (rather than injecting all 10 every time).

You could also consider splitting your class into smaller components rather than having to inject 10 different repositories.

I can't really imagine what architecture would call for 10 different tables in a single service; there's probably a neater way to set things up and avoid that altogether, if you show us what the 10 tables actually are someone might be able to suggest an easier way.