ORMLite SQL Server Update - servicestack

I have a table called PODetail with a primary Key of POno and ItemCode and I have the following:
[Route("/podetail/{POno}/{ItemCode}")]
public class UpdatePODetail : IReturn<PODetail> {
public string POno { get; set; }
public string ItemCode { get; set; }
public int ? QtyPend { get; set; }
public decimal ? NewPrice { get; set; }
public bool ? BackOrder { get; set; }
public string ActionCode { get; set; }
public bool ? OpenOrder { get; set; }
}
public class PODetailService : Service {
public object Any(UpdatePODetail request) {
var podetail = Db.SingleFmt<PODetail>("ItemCode = {0} AND POno = {1}", request.ItemCode, request.POno);
// var cap = new CaptureSqlFilter();
try {
Db.Update(podetail);
} catch {
// var sql = string.Join(";\n\n", cap.SqlStatements.ToArray());
}
:
:
try {
Db.Update(podetail);
} catch (Exception ex) {
string error = ex.Message;
}
return podetail;
}
}
I added the Db.Update call at the top just to check to see if there was some issue changing a column, but I get
Violation of PRIMARY KEY constraint 'aaaaaPoDetail_PK'. Cannot insert
duplicate key in object 'dbo.PODetail'.
So then I added the cap = line to see the SQL code which returns
UPDATE "PODetail" SET "NewItemCode"=#NewItemCode, "POno"=#POno, "Vendor"=#Vendor, "ActionCode"=#ActionCode, "Price"=#Price, "NewPrice"=#NewPrice, "CostPrice"=#CostPrice, "QtyOrd"=#QtyOrd, "QtyRcv"=#QtyRcv, "QtySPO"=#QtySPO, "QtyPend"=#QtyPend, "BackOrder"=#BackOrder, "OpenOrder"=#OpenOrder, "OrderDate"=#OrderDate, "InvoiceNo"=#InvoiceNo, "InvoiceVendor"=#InvoiceVendor, "InvoiceDate"=#InvoiceDate, "InvoiceDiscount"=#InvoiceDiscount, "QtyCancel"=#QtyCancel, "Qtylabels"=#Qtylabels, "REOVendor"=#REOVendor, "CurrentRcvQty"=#CurrentRcvQty, "SOPickQty"=#SOPickQty, "SOItem"=#SOItem, "QtyOther"=#QtyOther, "BackOrderCode"=#BackOrderCode WHERE "ItemCode"=#ItemCode
And then it runs fine uncommented -- no exceptions .. if I remove it it gets the Primary Key error
What is the deal -- why do I need that CaptureSqlFilter call -- or what I do I need to change so that it knows both PoNo and ItemCode are primary Keys or the update needs to say WHERE "ItemCode"=#ItemCode AND "POno"=#PONo? It almost seems as if it is trying to do an INSERT vs an UPDATE without the CaptureSqlFilter
Update 1
The documentation said :
Limitations For simplicity, and to be able to have the same POCO class
persisted in db4o, memcached, redis or on the filesystem (i.e.
providers included in ServiceStack), each model must have a single
primary key, by convention OrmLite expects it to be Id although you
use [Alias("DbFieldName")] attribute it map it to a column with a
different name or use the [PrimaryKey] attribute to tell OrmLite to
use a different property for the primary key.
You can still SELECT from these tables, you will just be unable to
make use of APIs that rely on it, e.g. Update or Delete where the
filter is implied (i.e. not specified), all the APIs that end with
ById, etc.
Workaround single Primary Key limitation
A potential workaround to support tables with multiple primary keys is
to create an auto generated Id property that returns a unique value
based on all the primary key fields,
So I tried to add this
public class PODetail {
public string Id { get { return this.ItemCode + "/" + this.POno; } }
public string ItemCode { get; set; }
public string NewItemCode { get; set; }
public string POno { get; set; }
:
}
But when it went to execute :
Db.SingleFmt<PODetail>
It error out with ID not a valid column or column not found or something like that
So I then tried
public class PODetail {
//public string Id { get { return this.ItemCode + "/" + this.POno; } }
[PrimaryKey]
public string ItemCode { get; set; }
public string NewItemCode { get; set; }
[PrimaryKey]
public string POno { get; set; }
:
}
and it worked on the Db.SingleFmt ... and the Db.Update
So then I added back in the CaptureSqlFilter to see what the query looked like and I got
UPDATE "PODetail" SET "NewItemCode"=#NewItemCode, "Vendor"=#Vendor, "ActionCode"=#ActionCode, "Price"=#Price, "NewPrice"=#NewPrice, "CostPrice"=#CostPrice, "QtyOrd"=#QtyOrd, "QtyRcv"=#QtyRcv, "QtySPO"=#QtySPO, "QtyPend"=#QtyPend, "BackOrder"=#BackOrder, "OpenOrder"=#OpenOrder, "OrderDate"=#OrderDate, "InvoiceNo"=#InvoiceNo, "InvoiceVendor"=#InvoiceVendor, "InvoiceDate"=#InvoiceDate, "InvoiceDiscount"=#InvoiceDiscount, "QtyCancel"=#QtyCancel, "Qtylabels"=#Qtylabels, "REOVendor"=#REOVendor, "CurrentRcvQty"=#CurrentRcvQty, "SOPickQty"=#SOPickQty, "SOItem"=#SOItem, "QtyOther"=#QtyOther, "BackOrderCode"=#BackOrderCode WHERE "ItemCode"=#ItemCode AND "POno"=#POno
Which is what I wanted in the first place.
It works but what is the deal can you have the [PrimaryKey] attribute multiple times (it appears so) and also then why didn't the autogenerated Id work? Just wondering if I am missing something or not understanding the documentation correctly.
Oh and sorry for posting in the comments!

what I do I need to change so that it knows both PoNo and ItemCode are
primary Keys
OrmLite's primary limitation is that each Table has a single primary Key.
Also you can use the built-in Profiling or debug logging to view the generated SQL without needing to change code to use CaptureSqlFilter.
I'd also recommend that you don't use the Request DTO for anything other than defining your Service with. You can use the built-in AutoMapping to easily use it to populate your data model.

Related

Error using Merge in Servicestack.OrmLite Sql Server

Using the latest version of https://github.com/ServiceStack/ServiceStack.OrmLite
[Schema("dbo")]
[Alias("ShelvingCount")]
public class ShelvingCount: IHasId<int>
{
[Alias("ShelvingCountId")]
[Index(Unique = true)]
[AutoIncrement]
public int Id { get; set;}
[Required]
[References(typeof(Account))]
public int AccountId { get; set; }
[Reference]
public Account Account { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
public int Quantity { get; set; }
[Required]
public int? Status { get; set; }
}
I removed the property EmployeeId which was a foreigh key to the Employees table. And I forgot to remove the "Merge command" in the code below:
var result = await dbCon.SqlListAsync<ShelvingCount>("EXEC getAllShelvingCounts #accountId, #status, #fromDate, #toDate", new { accountId, status, fromDate, toDate });
// Load the references
var employees = dbCon.Select<Employee>();
result.Merge(employees);
return result;
Then it resulted in the error below. I know that I should have removed the merge command. However, it can be fixed by ignoring the Merge command in cases when there is no reference to that table.
{ResponseStatus:{ErrorCode:Exception,Message:Could not find Child Reference for 'Employee' on Parent 'ShelvingCount',StackTrace:"[AllShelvingCounts: 24/06/2015 4:15:01 AM]:
[REQUEST: {AccountId:0,Status:-1,FromDate:2015-06-22,ToDate:2015-06-24}]
System.Exception: Could not find Child Reference for 'Employee' on Parent 'ShelvingCount'
at ServiceStack.OrmLite.OrmLiteUtils.Merge[Parent,Child](List`1 parents, List`1 children)
at Next.Management.Repository.ShelvingCountRepository.<GetAllShelvingCounts>d__0.MoveNext() in c:\dev\Next\Logistics\Management\src\Management.Repository\Repository\ShelvingCountRepository.cs:line 26
Is it some relevant issue to be fixed?
Taking into account that the exception might help the developer to remove the useless merge command, It might be interesting to alert the servicestack developers.
This is working as intended, the error message indicates that it couldn't find a static relationship that could be merged which negates the purpose of the Merge command - to merge related result sets. When there is no statically defined relationship that exists, this is clearly an error the developer should know about since their usage of the API is not working as intended.
This is the same as setting a non-existent/misspelt property in a statically typed language, i.e. the Compiler feedback is there to catch developer errors.

ServiceStack AutoQuery, Multiple IJoin

In my example I have the following database structure. Order has many OrderLine, which has one Product.
I am trying to return the following DTO:
public class OrderLineDto {
public int Id { get; set; }
public int Quantity { get; set; }
public string OrderType { get; set; }
public string ProductName { get; set; }
}
This should be possible by use of the following Query Route:
[Route("/orderlines")]
public class FindOrderLines : QueryBase<OrderLine, OrderLineDto>,
IJoin<OrderLine, Order>,
IJoin<OrderLine, Product>
{ }
What I am trying to do here is join OrderLine in both directions to bring in Type from Order, and Name from Product and return it in an OrderLineDto.
I am able to do these things individually by only using one IJoin, however AutoQuery appears only to use the first IJoin interface declaration, and does not perform the second join.
If I attempt to do a join like this: IJoin<OrderLine, Order, Product>
I get the following exception: Could not infer relationship between Order and Product
Is it possible to achieve what I am trying to do here with auto query or should I go back to writing standard REST services, abandoning AutoQuery?
I have submitted a pull request to ServiceStack which will now allow this behavior.
https://github.com/ServiceStack/ServiceStack/pull/955

Including a base member doesn't seem to work in Entity Framework 5

here are my entities:
public abstract class ResourceBase
{
[Key]
int Id { get; set; }
[ForeignKey("Resource")]
public Guid ResourceId { get; set; }
public virtual Resource Resource { get; set; }
}
public class Resource
{
[Key]
public Guid Id { get; set; }
public string Type { get; set; }
}
public class Message : ResourceBase
{
[MaxLength(300)]
public string Text { get; set; }
}
And then my query is something like this:
var msgs = messages.Where(x=>x.Id == someRangeOfIds).Include(m=>m.Resource).Select(x => new
{
message = x,
replyCount = msgs.Count(msg => msg.Id = magicNumber)
});
I am running this with proxy creation disabled, and the result is all the messages BUT with all the Resource properties as NULL. I checked the database and the Resources with matching Guids are there.
I drastically simplified my real life scenario for illustration purposes, but I think you'll find you can reproduce the issue with just this.
Entity Framework 5 handles inherited properties well (by flattening the inheritence tree and including all the properties as columns for the entity table).
The reason this query didn't work was due to the projection after the include. Unfortunately, the include statement only really works when you are returning entities. Although, I did see mention of a solution which is tricky and involves invoking the "include" after the shape of the return data is specified... If anyone has more information on this please reply.
The solution I came up with was to just rephrase the query so I get all messages in one query, and then in another trip to the database another query that gets all the reply counts.
2 round trips when it really should only be 1.

How update an entity inside Aggregate

I have an aggregate named Campaigns every with a root entity named campaign, this root entity has a list of attempts (entity)
public class Attempts: IEntity<Attempts>
{
private int id;
public AttempNumber AttemptNumber {get;}
//other fields
}
public class Campaign: IEntity<Campaign> //root
{
private int id;
public IList<Attempt> {get;}
//other fields
}
Im using a method to add a campaign attempt
public virtual void AssignAttempts(Attempts att)
{
Validate.NotNull(att, "attemps are required for assignment");
this.attempts.add(att);
}
Problem comes when i try to edit a specific item in attempts list. I get Attempt by AttempNumber and pass it to editAttempt method but i dont know how to set the attempt without deleting whole list and recreate it again
public virtual void EditAttempts(Attempts att)
{
Validate.NotNull(att, "attemps are required for assignment");
}
Any help will be appreciated!
Thanks,
Pedro de la Cruz
First, I think there may be a slight problem with your domain model. It seems to me like 'Campaign' should be an aggregate root entity having a collection of 'Attempt' value objects (or entities). There is no 'Campaigns' aggregate unless you have a parent concept to a campaign which would contain a collection of campaigns. Also, there is no 'Attempts' entity. Instead a collection of 'Attempt' entities or values on the 'Campaign' entity. 'Attempt' may be an entity if it has identity outside of a 'Campaign', otherwise it is a value object. The code could be something like this:
class Campaign {
public string Id { get; set; }
public ICollection<Attempt> Attempts { get; private set; }
public Attempt GetAttempt(string id) {
return this.Attempts.FirstOrDefault(x => x.Number == id);
}
}
class Attempt {
public string Number { get; set; }
public string Attribute1 { get; set; }
}
If you retrieve an Attempt from the Campaign entity and then change some of the properties, you should not have to insert it back into the campaign entity, it is already there. This is how the code would look if you were using NHibernate (similar for other ORMs):
var campaign = this.Session.Get<Campaign>("some-id");
var attempt = campaign.GetAttempt("some-attempt-id");
attempt.Attribute1 = "some new value";
this.Session.Flush(); // will commit changes made to Attempt
You don't need an Edit method. Your code can modify the Attempts in-place, like so:
Attempt toModify = MyRepository.GetAttemptById(id);
toModify.Counter++;
toModify.Location = "Paris";
MyRepository.SaveChanges(); // to actually persist to the DB
Of course how you name the SaveChanges() is up to you, this is the way Entity Framework names its general Save method.

Entity Framework 4 - TPH Inheritance in Features CTP5 (code first) with "IS NULL" discriminator

Hey guys,
I'm trying to create a TPH mapping on a hierarchy where the discriminating clause is the classical "IS NOT NULL" / "IS NULL" case.
Here is the example, database wise:
CREATE TABLE info.EducationTypes
(
ID INT NOT NULL PRIMARY KEY,
Name NVARCHAR(64) NOT NULL,
FKParentID INT NULL REFERENCES info.EducationTypes(ID)
)
the idea is to have a class hierarchy like the following one:
public abstract class EducationType
{
public int ID { get; set; }
public string Name { get; set; }
}
public class MainEducationType : EducationType
{
public IEnumerable<SubEducationType> SubTypes { get; set; }
}
public class SubEducationType : EducationType
{
public MainEducationType MainType { get; set; }
}
I got this schema "working" in the classic xml model, but I really can't find a way to get it working by using the code first approach. This is what I tried...
var educationType = modelBuilder.Entity<EducationType>();
educationType.Map<MainEducationType>(m => m.Requires("FKParentID").HasValue(null));
educationType.Map<SubEducationType>(m => m.Requires("FKParentID"));
Do you have any suggestion?
Unfortunately, having a null value for the discriminator column in TPH mapping is not currently supported in CTP5. This is confirmed by EF team on here and also here. They are looking at it to see if they can make it work for the RTM though.

Resources