ORMLite Service stack Self reference tables - servicestack

I have a class of companies and sub companies. These can be nested to any level and displayed in a treeview. I am trying to figure out how to do a self reference in ormlite to build out a hierarchy using the below DTO. With the below I get ambiguous column name errors. Is this approach a bad idea with Service stack?
public class Company : DTOServiceStackBase
{
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Address { get; set; }
[References(typeof(Company))]
public int ParentId { get; set; }
}
The below DTO works fine in ORMLite. I would prefer the cleaner implementation above.
public class Company : DTOServiceStackBase
{
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Address { get; set; }
[Reference] // Save in SubCompanies table
public List<SubCompany> SubCompanies { get; set; }
}
public class SubCompany : Company
{
[References(typeof(Company))]
public int ChildCompanyId { get; set; }
[References(typeof(Company))]
public int ParentCompanyId { get; set; }
}
EDIT Based on Mythz's Response
Here is my working code for anyone who wants to use it.
[Route("/Company/{Id}", "GET")]
public class GetCompaniesById : IReturn<GetCompaniesFlatTree>
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int? ParentId { get; set; }
}
[Route("/CompaniesFlatTree", "GET")]
public class GetCompaniesFlatTree : IReturn<GetCompaniesFlatTree>
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int? ParentId { get; set; }
}
[Route("/CompaniesTree", "GET")]
public class GetCompaniesTree : IReturn<Company>{}
public class DTOServiceStackBase {
public ResponseStatus ResponseStatus { get; set; } //Automatic exception handling
}
public class Company : DTOServiceStackBase
{
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Address { get; set; }
public int? ParentId { get; set; }
[IgnoreDataMember]
public List<Company> SubCompanies { get; set; }
}
[Authenticate]
public class CompanyService : Service
{
/// <summary>
/// Calling SQL directly and casting to the GetCompaniesFlatTree object
/// Don't do this methond of direct SQL unless you cannot do it any other way
/// Why?? Becuase the SQL is not automatically updated when we updated the database schema
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public object Get(GetCompaniesFlatTree request)
{
//This retun uses the DB.Select and works correctly
//return Db.Select<GetCompaniesFlatTree>($"SELECT SC.* FROM Company C Join Company SC ON SC.ParentId = C.Id Where C.ID = {request.Id}");
//This query uses Db.Query due to the BEGIN and CTE Usage
//This does not work with SQL in Memory because it does not support CTE Statements
return Db.Query<GetCompaniesFlatTree>("BEGIN WITH q AS ( SELECT * FROM [Company] WHERE ParentId IS NULL UNION ALL SELECT m.* FROM [Company] m JOIN q ON m.parentId = q.Id) SELECT * FROM q END;");
}
/// <summary>
/// Table Alias is required in this Select due to the self join on company.
/// Table Alisa allows the join to specify which table to return the data from.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public object Get(GetCompaniesById request)
{
var q = Db.From<Company>(Db.TableAlias("c1"))
.Join<Company>((ChildComp, ParentCompany) =>
ChildComp.Id == ParentCompany.ParentId
&& ParentCompany.Id == request.Id, Db.TableAlias("c2")).Select<Company>(p => new {Id = Sql.TableAlias(p.Id, "c2"), Name = Sql.TableAlias(p.Name, "c2")});
var results = Db.Select<GetCompaniesById>(q);
//See the SQL that was generated
var lastSql = Db.GetLastSql();
return results;
}
/// <summary>
/// Get all Compaines and build the hierarchy
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public object Get(GetCompaniesTree request)
{
//Get all companies
var results = Db.Select<Company>();
//Get Top node
Company topCompany = results.Single(x => x.ParentId == null);
//Find all children
var allChildrenRecursive = GetAllChildrenRecursive(topCompany, results);
return allChildrenRecursive;
}
/// <summary>
/// Populates a Companies collection of child companies
/// </summary>
/// <param name="parent"></param>
/// <param name="results"></param>
/// <returns></returns>
private Company GetAllChildrenRecursive(Company parent, List<Company> results)
{
List<Company> retVal = new List<Company>();
retVal.Add(parent);
//Get Children
var children = results.Where(x => x.ParentId == parent.Id).ToList();
parent.SubCompanies = children;
foreach (var child in children)
{
GetAllChildrenRecursive(child, results);
}
return parent;
}
}

To maintain a tree relationship you would just need to have a nullable int? ParentId in the Company table where Company with NULL ParentId is the root company whilst iterating through the rest of the companies to populate a Dictionary<int,List<Company>> indexed by the parent Id.
This isn't related to an OrmLite Self Reference which just means to maintain the FK Reference to a different table on the table containing the reference.

Related

Autquery not including nested result when using a response DTO

Let's say you have these models:
public class Blog
{
[PrimaryKey]
[AutoIncrement]
public int Id { get; set; }
public string Url { get; set; }
public string PrivateField { get; set; }
[Reference]
public List<BlogToBlogCategory> BlogToBlogCategories { get; set; }
}
public class BlogResponse
{
public int Id { get; set; }
public string Url { get; set; }
public List<BlogToBlogCategory> BlogToBlogCategories { get; set; }
}
And this request:
public class BlogsLookUpRequest : QueryDb<Blog, BlogResponse>
{
}
The return value will have BlogToBlogCategories as null, but this request:
public class BlogsLookUpRequest : QueryDb<Blog>
{
}
Will have BlogToBlogCategories populated. I can manually create the query response like so with custom implementation:
var q = _autoQuery.CreateQuery(request, Request.GetRequestParams(), base.Request);
var results = _autoQuery.Execute(request,q, base.Request);
return new QueryResponse<ResponseBlog>()
{
Results = results.Results.ConvertTo<List<ResponseBlog>>(),
Offset = request.Skip,
Total = results.Total
};
Then it will have the nested results. If I decorate the collection with [Reference] then it is trying to find foreign key on non-existant BlogResponse table.
Why are referenced results removed when specifying a return model with AutoQuery? Is there a way to mark it up so it works?
The POCO Reference Types is used to populate Data Models not adhoc Response DTOs.
In this case it's trying to resolve references on a non-existent table, you can specify which table the DTO maps to with [Alias] attribute, e.g:
[Alias(nameof(Blog))]
public class BlogResponse
{
public int Id { get; set; }
public string Url { get; set; }
public List<BlogToBlogCategory> BlogToBlogCategories { get; set; }
}

Microsoft Power Automate Alternative for listening events in Azure DevOps

Goal:
Listen to events in Azure DevOps and automate workflows in Azure DevOps, like closing the tasks etc,.
Efforts:
I am using MS Power Automate to listen to events in Azure DevOps but it seems to work too slow (1-2 mins since the trigger).
Suggestion Required:
Do we have any alternative to MS Power Automate that can reduce the time ?
You may try to programmatically create a subscription using the Subscriptions REST APIs:
https://learn.microsoft.com/en-us/azure/devops/service-hooks/create-subscription?view=azure-devops
Here's a sample to help you get started:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Mvc;
namespace Microsoft.Samples.VisualStudioOnline
{
public class ServiceHookEventController : Controller
{
// POST: /ServiceHookEvent/workitemcreated
[HttpPost]
public HttpResponseMessage WorkItemCreated(Content workItemEvent)
{
//Grabbing the title for the new workitem
var value = RetrieveFieldValue("System.field", workItemEvent.Resource.Fields);
//Acknowledge event receipt
return new HttpResponseMessage(HttpStatusCode.OK);
}
/// <summary>
/// Gets the value for a specified work item field.
/// </summary>
/// <param name="key">Key used to retrieve matching value</param>
/// <param name="fields">List of fields for a work item</param>
/// <returns></returns>
public String RetrieveFieldValue(String key, IList<FieldInfo> fields)
{
if (String.IsNullOrEmpty(key))
return String.Empty;
var result = fields.Single(s => s.Field.RefName == key);
if (result == null)
return String.Empty;
return result.Value;
}
}
public class Content
{
public String SubscriptionId { get; set; }
public int NotificationId { get; set; }
public String EventType { get; set; }
public WorkItemResource Resource { get; set; }
}
public class WorkItemResource
{
public String UpdatesUrl { get; set; }
public IList<FieldInfo> Fields { get; set;}
public int Id { get; set; }
public int Rev { get; set; }
public String Url { get; set; }
public String WebUrl { get; set; }
}
public class FieldInfo
{
public FieldDetailedInfo Field { get; set; }
public String Value { get; set; }
}
public class FieldDetailedInfo
{
public int Id { get; set; }
public String Name { get; set; }
public String RefName { get; set; }
}
}

Conversion failed,when using AutoQuery in ServiceStack

I have the following AutoQuery function.
[Route("/cars/search")]
public class SearchCars : QueryDb<Car, CarDto>
{
public List<int> EquipmentIds { get; set; }
public List<int> ManufacturerIds { get; set; }
public List<int> ColourIds { get; set; }
}
The function works, when I do the following:
Cars/Search?ColourIds=1&format=json
Cars/Search?ManufacturerIds=1&format=json
but when I try to use
Cars/Search?EquipmentIds=1&format=json
I get "Conversion failed when converting the varchar value '[1]' to data type int.".
The difference between these fields is that Car object can have multiple EquipmentIds, but only one ColourId and ManufacturerId.
public class Car
{
[AutoIncrement]
public int Id { get; set; }
public Colour Colour { get; set; }
[Required]
public int ColourId { get; set; }
public Manufacturer Manufacturer { get; set; }
[Required]
public int ManufacturerId { get; set; }
[Required]
public List<Equipment> Equipment { get; set; }
[Required]
public List<int> EquipmentId { get; set; }
}
Do I have to define for which attribute the different parameters should be assigned too?
AutoQuery works by constructing an RDBMS query based on implicit conventions which is used to construct an SQL query that runs on the RDBMS.
Complex Types in OrmLite data models are blobbed by default which means they can't be queried in the RDBMS with SQL, so you wont be able to query it with AutoQuery.
You could create a hybrid Custom AutoQuery Implementation where you can apply any custom logic to filter the results of the AutoQuery results, something like...
public class MyQueryServices : Service
{
public IAutoQueryDb AutoQuery { get; set; }
//Override with custom implementation
public object Any(SearchCars query)
{
var equipmentIds = query.EquipmentIds;
query.EquipmentIds = null;
var q = AutoQuery.CreateQuery(query, base.Request);
var response = AutoQuery.Execute(query, q);
if (equipmentIds != null)
response.Results.RemoveAll(x => x.EquipmentId...);
return response.
}
}

Automapper projection results in empty collection for nested Dto

I have a .Net Core 2 webapi in which I am using automapper to map to Dtos. Everything works fine, except I am seeing an unexpected behaviour when I map an object to a Dto, and where the Dto also contains mappings for a collection. E.g
CreateMap<Order, OrderDto>();
CreateMap<Product, ProductDto>();
Where classes are like this
public partial class Order
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products{ get; set; }
public int ProductCount {return Products.Count;}
}
public partial class Product
{
public int Id { get; set; }
public int OrderId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
The following works as expected;
The class is mapped, and the ProjectCount is correct in the Dto
public partial class OrderDto
{
public int Id { get; set; }
public virtual ICollection<Product> Products{ get; set; }
public int ProductCount{ get; set; }
}
_context.Orders.Include<>(Products).ProjectTo<>(OrderDto)
But doing the following, the productcount is always zero.
E.g. if I do this;
public partial class OrderDto
{
public int Id { get; set; }
public virtual ICollection<ProductDto> Products{ get; set; }
public int ProductCount{ get; set; }
}
public partial class ProductDto
{
public int Id { get; set; }
public int OrderId { get; set; }
public string Name { get; set; }
}
_context.Orders.Include<>(Products).ProjectTo<>(OrderDto)
Why does this happen, and how can I ensure that it doesnt? This is a real world example where I need a property which references the collection - and I need it in both the base and the Dto. I can do the following which works fine, but it doesnt appear that this should be how it works...
public partial class OrderDto
{
public int Id { get; set; }
public virtual ICollection<ProductDto> Products{ get; set; }
public int ProductCount {return Products.Count;}
}
public partial class ProductDto
{
public int Id { get; set; }
public string Name { get; set; }
}
_context.Orders.Include<>(Products).ProjectTo<>(OrderDto)
I profiled the SQL and found that Automapper changes the way the query is formed. Without the nested projection, two queries are made;
[Queries are more complex than this and use joins, but you get the idea]
Select Id from orders
Select Id,Name from products where productid in [select id from orders ]
With the nested projection, are executed for each nested Dto
Select Id from orders
Select Id,Name from products where id=1
Select Id,Name from products where id=2

Azure Table Storage - TableEntity map column with a different name

I am using Azure Table Storage as my data sink for my Semantic Logging Application Block. When I call a log to be written by my custom EventSource, I get columns similar to the ff.:
EventId
Payload_username
Opcode
I can obtain these columns by creating a TableEntity class that matches the column names exactly (except for EventId, for some reason):
public class ReportLogEntity : TableEntity
{
public string EventId { get; set; }
public string Payload_username { get; set; }
public string Opcode { get; set; }
}
However, I would like to store the data in these columns in differently named properties in my TableEntity:
public class ReportLogEntity : TableEntity
{
public string Id { get; set; } // maps to "EventId"
public string Username { get; set; } // maps to "Payload_username"
public string Operation { get; set; } // maps to "Opcode"
}
Is there a mapper/attribute I can make use of to allow myself to have the column name different from the TableEntity property name?
You can override ReadEntity and WriteEntity methods of interface ITableEntity to customize your own property names.
public class ReportLogEntity : TableEntity
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string Id { get; set; } // maps to "EventId"
public string Username { get; set; } // maps to "Payload_username"
public string Operation { get; set; } // maps to "Opcode"
public override void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
{
this.PartitionKey = properties["PartitionKey"].StringValue;
this.RowKey = properties["RowKey"].StringValue;
this.Id = properties["EventId"].StringValue;
this.Username = properties["Payload_username"].StringValue;
this.Operation = properties["Opcode"].StringValue;
}
public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
{
var properties = new Dictionary<string, EntityProperty>();
properties.Add("PartitionKey", new EntityProperty(this.PartitionKey));
properties.Add("RowKey", new EntityProperty(this.RowKey));
properties.Add("EventId", new EntityProperty(this.Id));
properties.Add("Payload_username", new EntityProperty(this.Username));
properties.Add("Opcode", new EntityProperty(this.Operation));
return properties;
}
}

Resources