Saving a collection of records in Orchard - orchardcms

Currently I have a part that has 3 fields (Name, Value1, Value2). I have everything working where I can do a Create/Edit/Delete on the part.
What I want to do now is have a grid with 3 columns (Name, Value1, Value2) and can have multiple rows (up to the user how many there will be). The save won't happen until the user done (save all rows in a single post back).
I haven't figured what is needed so a collection of items will get saved on post back.
Any suggestions on how to do this?
Thanks!

What you could have is to have, in the part, a collection of the records corresponding to (Name, Value1, Value2) by having your dbms create and manage a 1-to-n relationship.
For example, you would have
public class ThisIsYourPart : ContentPart<ThisIsYourPartRecord> {
// You can access the list of your records as
// yourPart.Record.YourRecords
}
public class ThisIsYourPartRecord : ContentPartRecord {
public ThisIsYourPartRecord () {
YourRecords= new List<YourRecordWithValues>();
}
public virtual IList<YourRecordWithValues> YourRecords{ get; set; }
}
public class YourRecordWithValues {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Value1 { get; set; } // use your actual type
public virtual ThisIsYourPartRecord ThisIsYourPartRecord { get; set; }
}
public class YourMigration : DataMigrationImpl {
public int Create() {
SchemaBuilder.CreateTable("YourRecordWithValues ", table => table
.Column<int>("Id", col => col.Identity().PrimaryKey())
.Column<string>("Name", col => col.NotNull().Unlimited())
.Column<string>("Value1", col => col.NotNull().Unlimited())
.Column<int>("ThisIsYourPartRecord_Id"));
SchemaBuilder.CreateTable("ThisIsYourPartRecord", table => table
.ContentPartRecord());
}
}
Code like that should do it.
We used this kind of relations a lot in https://github.com/bleroy/Nwazet.Commerce
*edit:
of course, have all the code in the proper files and folders.

Related

Servicestack - possibility of mapping several POCO to one table

I'm looking for a way to map several POCO objects into single table in the ServiceStack.
Is it possible to do this in a clean way, without "hacking" table creation process?
As a general rule, In OrmLite: 1 Class = 1 Table.
But I'm not clear what you mean my "map several POCO objects into single table", it sounds like using Auto Mapping to populate a table with multiple POCO instances, e.g:
var row = db.SingleById<Table>(id);
row.PopulateWithNonDefaultValues(instance1);
row.PopulateWithNonDefaultValues(instance2);
db.Update(row);
If you need to maintain a single table and have other "sub" classes that maintain different table in the universal table you can use [Alias] so all Update/Select/Insert's reference the same table, e.g:
public class Poco
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
[Alias(nameof(Poco))]
public class PocoName
{
public int Id { get; set; }
public string Name { get; set; }
}
[Alias(nameof(Poco))]
public class PocoAge
{
public int Id { get; set; }
public int Age { get; set; }
}
Although I don't really see the benefit over having a single table that you use AutoMapping to map your other classes to before using that in OrmLite.

ServiceStack - [Reference] or [Ignore]?

We have a DTO - Employee - with many (> 20) related DTOs and DTO collections. For "size of returned JSON" reasons, we have marked those relationships as [Ignore]. It is then up to the client to populate any related DTOs that they would like using other REST calls.
We have tried a couple of things to satisfy clients' desire to have some related Employee info but not all:
We created a new DTO - EmployeeLite - which has the most-requested fields defined with "RelatedTableNameRelatedFieldName" approach and used the QueryBase overload and that has worked well.
We've also tried adding a property to a request DTO - "References" - which is a comma-separated list of related DTOs that the client would like populated. We then iterate the response and populate each Employee with the related DTO or List. The concern there is performance when iterating a large List.
We're wondering if there a suggested approach to what we're trying to do?
Thanks for any suggestions you may have.
UPDATE:
Here is a portion of our request DTO:
[Route("/employees", "GET")]
public class FindEmployeesRequest : QueryDb<Employee> {
public int? ID { get; set; }
public int[] IDs { get; set; }
public string UserID { get; set; }
public string LastNameStartsWith { get; set; }
public DateTime[] DateOfBirthBetween { get; set; }
public DateTime[] HireDateBetween { get; set; }
public bool? IsActive { get; set; }
}
There is no code for the service (automagical with QueryDb), so I added some to try the "merge" approach:
public object Get(FindEmployeesRequest request) {
var query = AutoQuery.CreateQuery(request, Request.GetRequestParams());
QueryResponse<Employee> response = AutoQuery.Execute(request, query);
if (response.Total > 0) {
List<Clerkship> clerkships = Db.Select<Clerkship>();
response.Results.Merge(clerkships);
}
return response;
}
This fails with Could not find Child Reference for 'Clerkship' on Parent 'Employee'
because in Employee we have:
[Ignore]
public List<Clerkship> Clerkships { get; set; }
which we did because we don't want "Clerkships" with every request. If I change [Ignore] to [Reference] I don't need the code above in the service - the List comes automatically. So it seems that .Merge only works with [Reference] which we don't want to do.
I'm not sure how I would use the "Custom Load References" approach in an AutoQuery service. And, AFAIKT, the "Custom Fields" approach can't be use for related DTOs, only for fields in the base table.
UPDATE 2:
The LoadSelect with include[] is working well for us. We are now trying to cover the case where ?fields= is used in the query string but the client does not request the ID field of the related DTO:
public partial class Employee {
[PrimaryKey]
[AutoIncrement]
public int ID { get; set; }
.
.
.
[References(typeof(Department))]
public int DepartmentID { get; set; }
.
.
.
public class Department {
[PrimaryKey]
public int ID { get; set; }
public string Name { get; set; }
.
.
.
}
So, for the request
/employees?fields=id,departmentid
we will get the Department in the response. But for the request
/employees?fields=id
we won't get the Department in the response.
We're trying to "quietly fix" this for the requester by modifying the query.SelectExpression and adding , "Employee"."DepartmentID" to the SELECT before doing the Db.LoadSelect. Debugging shows that query.SelectExpression is being modified, but according to SQL Profiler, "Employee"."DepartmentID" is not being selected.
Is there something else we should be doing to get "Employee"."DepartmentID" added to the SELECT?
Thanks.
UPDATE 3:
The Employee table has three 1:1 relationships - EmployeeType, Department and Title:
public partial class Employee {
[PrimaryKey]
[AutoIncrement]
public int ID { get; set; }
[References(typeof(EmployeeType))]
public int EmployeeTypeID { get; set; }
[References(typeof(Department))]
public int DepartmentID { get; set; }
[References(typeof(Title))]
public int TitleID { get; set; }
.
.
.
}
public class EmployeeType {
[PrimaryKey]
public int ID { get; set; }
public string Name { get; set; }
}
public class Department {
[PrimaryKey]
public int ID { get; set; }
public string Name { get; set; }
[Reference]
public List<Title> Titles { get; set; }
}
public class Title {
[PrimaryKey]
public int ID { get; set; }
[References(typeof(Department))]
public int DepartmentID { get; set; }
public string Name { get; set; }
}
The latest update to 4.0.55 allows this:
/employees?fields=employeetype,department,title
I get back all the Employee table fields plus the three related DTOs - with one strange thing - the Employee's ID field is populated with the Employee's TitleID values (I think we saw this before?).
This request fixes that anomaly:
/employees?fields=id,employeetypeid,employeetype,departmentid,department,titleid,title
but I lose all of the other Employee fields.
This sounds like a "have your cake and eat it too" request, but is there a way that I can get all of the Employee fields and selective related DTOs? Something like:
/employees?fields=*,employeetype,department,title
AutoQuery Customizable Fields
Not sure if this is Relevant but AutoQuery has built-in support for Customizing which fields to return with the ?fields=Field1,Field2 option.
Merge disconnected POCO Results
As you've not provided any source code it's not clear what you're trying to achieve or where the inefficiency with the existing solution lies, but you don't want to be doing any N+1 SELECT queries. If you are, have a look at how you can merge disconnected POCO results together which will let you merge results from separate queries based on the relationships defined using OrmLite references, e.g the example below uses 2 distinct queries to join Customers with their orders:
//Select Customers who've had orders with Quantities of 10 or more
List<Customer> customers = db.Select<Customer>(q =>
q.Join<Order>()
.Where<Order>(o => o.Qty >= 10)
.SelectDistinct());
//Select Orders with Quantities of 10 or more
List<Order> orders = db.Select<Order>(o => o.Qty >= 10);
customers.Merge(orders); // Merge disconnected Orders with their related Customers
Custom Load References
You can selectively control which references OrmLite should load by specifying them when you call OrmLite's Load* API's, e.g:
var customerWithAddress = db.LoadSingleById<Customer>(customer.Id,
include: new[] { "PrimaryAddress" });
Using Custom Load References in AutoQuery
You can customize an AutoQuery Request to not return any references by using Db.Select instead of Db.LoadSelect in your custom AutoQuery implementation, e.g:
public object Get(FindEmployeesRequest request)
{
var q = AutoQuery.CreateQuery(request, Request);
var response = new QueryResponse<Employee>
{
Offset = q.Offset.GetValueOrDefault(0),
Results = Db.Select(q),
Total = (int)Db.Count(q),
};
return response;
}
Likewise if you only want to selectively load 1 or more references you can change LoadSelect to pass in an include: array with only the reference fields you want included, e.g:
public object Get(FindEmployeesRequest request)
{
var q = AutoQuery.CreateQuery(request, Request);
var response = new QueryResponse<Employee>
{
Offset = q.Offset.GetValueOrDefault(0),
Results = Db.LoadSelect(q, include:new []{ "Clerkships" }),
Total = (int)Db.Count(q),
};
return response;
}

ServiceStack ORMLite how to not serialize list

I don't know how to store collection (Comments) in separate table.
By default comments are serialized and stored in SomeClass table as column Comments.
[{Id:0,CreateDate:2013-09-12T14:28:37.0456202+02:00,,SomeClassID:1,CommentText:"coment text",}]
Is there any way to save it in separate tables?
public class SomeClass {
[AutoIncrement]
public int Id { get; set; }
public string Title { get; set; }
List<Comment> comments = new List<Comment>();
public List<Comment> Comments {
get { return comments; }
set { comments = value; }
}
}
public class Comment {
[AutoIncrement]
public int Id { get; set; }
[References(typeof(SomeClass))]
public int SomeClassID { get; set; }
[StringLength(4000)]
public string CommentText { get; set; }
}
I don't think ORMLite supports serializing to multiple tables. 1 table = 1 class so the comments will be stored as a Blob field in the SomeClass table.
If you need to store them in separate tables you will have to save the comments separately and have a foreign key reference back to the id of the SomeClass table.

Orchard data insert/delete for non content item

I am intending to insert/delete some information in a module's Action (using Orchard Rules-Action API) in a one-column table in the database. What is the best way of doing such tasks i.e. Data manipulation of non-content items. I do not want to go by the "Create a content type" route. I simply want to persist some non-content data in the database and query/delete them.
namespace xyz.Models
{
public class Task
{
public virtual int ContentId { get; set; }
public virtual int Retries { get; set; }
}
}
SchemaBuilder.CreateTable("Task",
table => table
.Column<int>("ContentId")
.Column<int>("Retries")
);
return 1;
namespace Xyz.Services
{
public class TaskService : ITaskService
{
private readonly IRepository<Task> _taskRepository;
public TaskService(IRepository<Task> taskRepository)
{
_taskRepository = taskRepository;
}
public Task CreateTask(int contentId)
{
var task = new Task { ContentId = contentId };
_taskRepository.Create(task);
return task;
}
}
}
If you mean "creating a table without ContentPart" by non-content, then just create your desired model in the models folder :
public class MyRecord{
public virtual int Id { get; set; }
public virtual string FOO{ get; set; }
public virtual string BAR{ get; set; }
}
and obviously you must create a table in migration as following :
SchemaBuilder.CreateTable("MyRecord",
table => table
.Column<int>("Id", c => c.PrimaryKey().Identity())
.Column<string>("FOO")
.Column<string>("BAR")
);
and finally where you want to have a transaction over table ,simply inject an instance of your model's repository :
private readonly IRepository<MyRecord> _repository;
public SomeClass(IRepository<MyRecord> repository){
_repository = repository;
}
public SomeMethod(){
var record = new MyRecord();
//initialize your class here
_repository.Create(record);
}
Important to note is that your record class must be in the Models folder and must contain an Id property.

Entity Framework - Single Entity to Multiple Tables

I am having some difficulty in mapping single entity to a two different tables in a Entity Framework out of which one is optional to give a quick overview.
I have one main table which is of a core table that lot of our applications in our company uses it, so we really don't want to make any changes to this table.
In our new application we needed a few more columns to support some of the features we are adding.
I have created a single Entity Model that will save information to both these tables, it is working fine when both these tables has the records (related by primary key and foreign key)
But for the historical record this new table will not have a associated record and not able to fetch any entity set.
Below is the code snippet.
public class ModelTable
{
public string PatientID { get; set; }
public string Diagnosis1 { get; set; }
public string Diagnosis2 { get; set; }
public string Diagnosis3 { get; set; }
public string Diagnosis4 { get; set; }
public string Diagnosis5 { get; set; }
public string Diagnosis6 { get; set; }
public string Diagnosis7 { get; set; }
public string Diagnosis8 { get; set; }
}
public class ModelTableMap : EntityTypeConfiguration<ModelTable>
{
public ModelTableMap()
{
//Table1
this.Map(model =>
{
model.Properties(table1 => new
{
table1.Diagnosis1,
table1.Diagnosis2,
table1.Diagnosis3,
table1.Diagnosis4,
table1.Diagnosis5,
table1.Diagnosis6
});
model.ToTable("Table1");
});
//Optional Table
this.Map(model =>
{
model.Properties(table2 => new
{
table2.Diagnosis7,
table2.Diagnosis8,
});
model.ToTable("Table2");
});
this.HasKey(type => type.PatientID);
this.Property(type => type.PatientID).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(type => type.Diagnosis1).HasColumnName("Diag1");
this.Property(type => type.Diagnosis1).HasColumnName("Diag2");
this.Property(type => type.Diagnosis1).HasColumnName("Diag3");
this.Property(type => type.Diagnosis1).HasColumnName("Diag4");
this.Property(type => type.Diagnosis1).HasColumnName("Diag5");
this.Property(type => type.Diagnosis1).HasColumnName("Diag6");
this.Property(type => type.Diagnosis1).HasColumnName("Diag7");
this.Property(type => type.Diagnosis1).HasColumnName("Diag8");
}
}
If I split these tables into a two different POCO classes and specify the relationshipt it is working fine.
But I want to achieve this with Single Entity, since functionally it is a same table.
Please provide any guidance or if I am doing any wrong and please bare with my English is not that good.
Thanks
Sathish
Entity splitting in current EF version requires records in both tables. If you want to use entity splitting you must create empty record for all existing records from the first table. Otherwise you cannot use entity splitting.

Resources