ServiceStack AutoQuery crash on synthetic field - servicestack-autoquery

This is a follow up on: ServiceStack AutoQuery synthetic field
.NET Core empty web template on newest 5.x versions of SS and .Net Core.
I'm trying to create an AutoQuery service that I can decorate with a few synthetic fields (i.e. fields that don't come from the database). So I've got this AutoQuery service with the following Data Transfer Object:
public class DataSource {
[Ignore]
public string Hello { get { return "Hello there"; }}
public string DataSourceId { get; set; }
public string DataSourceName { get; set; }
public int DataSourceSort { get; set; }
public bool DataSourceDisabled { get; set; }
public DateTime LastModified { get; set; }
}
When I don't include the public string Hello it all works.
The service itself is just a on-liner:
[Route("/query/datasources")]
public class QueryDatasources : QueryDb<DataSource> {}
This is the error I'm getting:
Offset0Total0Response Status
Error CodeInvalidOperationExceptionMessageSequence contains no matching elementStack Trace[QueryDatasources: 22/03/2019 17:47:41]: [REQUEST: {}] System.InvalidOperationException: Sequence contains no matching element at System.Linq.Enumerable.First[TSource](IEnumerable'1 source, Func'2 predicate) at ServiceStack.OrmLite.OrmLiteDialectProviderBase'1.GetLoadChildrenSubSelect[From](SqlExpression'1 expr) in C:\BuildAgent\work\27e4cc16641be8c0\src\ServiceStack.OrmLite\OrmLiteDialectProviderBase.cs:line 1616 at ServiceStack.OrmLite.SqlServer.SqlServerOrmLiteDialectProvider.GetLoadChildrenSubSelect[From](SqlExpression'1 expr) in C:\BuildAgent\work\27e4cc16641be8c0\src\ServiceStack.OrmLite.SqlServer\SqlServerOrmLiteDialectProvider.cs:line 587 at ServiceStack.OrmLite.Support.LoadList'2..ctor(IDbCommand dbCmd, SqlExpression'1 q) in C:\BuildAgent\work\27e4cc16641be8c0\src\ServiceStack.OrmLite\Support\LoadList.cs:line 46 at ServiceStack.OrmLite.OrmLiteReadCommandExtensions.LoadListWithReferences[Into,From](IDbCommand dbCmd, SqlExpression'1 expr, IEnumerable'1 include) in C:\BuildAgent\work\27e4cc16641be8c0\src\ServiceStack.OrmLite\OrmLiteReadCommandExtensions.cs:line 957 at ServiceStack.OrmLite.OrmLiteExecFilter.Exec[T](IDbConnection dbConn, Func'2 filter) in C:\BuildAgent\work\27e4cc16641be8c0\src\ServiceStack.OrmLite\OrmLiteExecFilter.cs:line 64 at ServiceStack.TypedQuery'2.Execute[Into](IDbConnection db, ISqlExpression query) in C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack.Server\AutoQueryFeature.cs:line 1089

The issue is because your data model doesn't have an explicit Primary Key.
In OrmLite each model must have a single primary key, by convention OrmLite expects it to be named Id and you can 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.
If your model doesn't have an explicit [PrimaryKey] attribute it will use the first [AutoIncrement] or [AutoId] on your model, if none of these exists it fallsback to using the first property as the primary key in which case is an ignored property.
I've removed ignored properties from consideration in this commit, however you should be explicit in which field to use as your Primary Key (using any of the above attributes or Id naming convention) instead of relying on OrmLite's fallback heuristic.

Related

Entity Framework Core: using navigation properties without foreign key

I have following object model:
public class SharingRelation:BaseEntity
{
public Guid? Code { get; set; }
public string Value { get; set; }
}
public class SecondLevelShareEntity : BaseEntity
{
public string Name { get; set; }
public Guid? SharingCode { get; set; }
public List<SharingRelation> SharingRelations { get; set; }
}
In my database (it may be poor db design but I need to answer this question for research), SharingRelation is some sort of dependent entity of SecondLevelShareEntity on Code == SharingCode values. I can have two entities of type SecondLevelShareEntity with same SharingCode value. So, for each of them I need to get all related SharingRelation objects depending on Code and SharingCode values. I can do it using SQL and join on this columns. But how can I do it using EF Core and navigation properties (I want to get all dependent entities using Include() for example)? When I configure my entities like this
public class SharingRelationEntityTypeConfiguration : BaseEntityTypeConfiguration<SharingRelation>
{
public override void Configure(EntityTypeBuilder<SharingRelation> builder)
{
base.Configure(builder);
builder.HasOne<SecondLevelShareEntity>().WithMany(x => x.SharingRelations).HasForeignKey(x => x.Code)
.HasPrincipalKey(x => x.SharingCode);
}
}
EF Core creates foreign key and marks it unique. I am obviously getting an error that that is impossible to have several SecondLevelShareEntity with the same SharingCode
System.InvalidOperationException : The instance of entity type 'SecondLevelShareEntity' cannot be tracked because another instance with the key value '{SharingCode: 8a4da9b3-4b8e-4c91-b0e3-e9135adb9c66}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
How can I avoid creation of foreign key, but keep using navigation properties (as far, as I see normal queries with navigations generate simple JOIN statements)
UPDATED I can provide real data in database. SecondLevelShareEntity table looks like this:
_id Name SharingCode
----------------------------------------------------------------------
1 "firstSecondLevelEnt" "efcb1c96-0ef1-4bb3-a952-4a6511ab448b"
2 "secondSecondLevelEnt" "efcb1c96-0ef1-4bb3-a952-4a6511ab448b"
And SharingRelation table looks like this:
_id Value Code
----------------------------------------------------------------------
1 "firstSharingRelation" "efcb1c96-0ef1-4bb3-a952-4a6511ab448b"
2 "secondSharingRelation" "efcb1c96-0ef1-4bb3-a952-4a6511ab448b"

RavenDB SaveChanges() not saving properties on derived class ([DataMember] used in other class)

I've recently upgraded to build 2230, and things are working just fine. However, I just updated the RavenDB .NET client assemblies and now I'm having this issue.
This code has been in place for a year or so. This is how I'm saving:
public void Save(EntityBase objectToSave)
{
using (IDocumentSession session = GetOptimisticSession())
{
session.Store(objectToSave, objectToSave.Etag);
session.SaveChanges();
}
}
And this is the object I'm saving.
public class InstallationEnvironment : EntityBase
{
public string Name { get; set; }
public int LogicalOrder { get; set; }
}
Now the base class:
public class EntityBase : NotifyPropertyChangedBase
{
public string Id { get; set; } // Required field for all objects with RavenDB.
}
The problem is that the base class property (Id) is getting persisted in RavenDB, but the derived properties (Name, LogicalOrder) are not.
Why would only the base class properties be saved in RavenDB?
Got it. Through trial and error, I noticed that one derived property was being saved (on a different class than the one shown in my question), and that property was decorated with the [DataMember] attribute. I just recently added it because I'm creating a WCF service for my app, and I started by using that attribute on one property for testing.
As Ayende states here, you have to use [DataMember] on all properties, or on none of them. If [DataMember] exists on a property, all others will be ignored.
Note: This was a problem for me even though [DataMember] was specified on a property in a different class. It seems like if I use [DataMember] anywhere, I have to use it for everything.

NHibernate not updating all properties of entities

I'm experiencing an odd problem with FluentNHibernate: when I save my entity, one of the (reference) properties is not updated. Other properties, both fields and references, are updated, and the failing property is correctly mapped (retrieving entities works like a charm).
A (slightly simplified) description of what I'm doing:
Into my MVC action method, an InputModel is bound and set. It has a property for the TypeID, where I wish to set the Type of my entity (let's call the entity type Thing).
A new Thing object is created, and the simple properties of the InputModel is copied over. For a couple of complex properties, among them the Type property which isn't working and another property which is, the following is done:
2.1. The correct ThingType is fetched from the repository, based on the provided type id.
2.2. The type is set (using thing.Type = theType) on the new Thing object.
The Thing that I want to update is fetched from the repository, based on the id on the input model (not the same id as the TypeID).
All properties, complex and other, are copied over from the new thing (created by me) to the original one (fetched from db).
The original Thing is saved, using session.Save();.
As stated above, it's only one property that isn't working - other properties, following (as far as I can tell) the exact same pattern, work. I've also debugged and verified that the original Thing has the correct, updated Type when it is passed to session.Save().
I have no idea where to start troubleshooting this...
Update: The classes are plain POCOs:
public class Thing
{
public int ID { get; set; }
public string SomeSimpleProp { get; set; }
public ThingType Type { get; set; }
public OtherEntity OtherReference { get; set; }
}
public class ThingType
{
public int ID { get; set; }
public string Name { get; set; }
}
My exact mappings (except for the names of types and properties) are these:
// In ThingMap : ClassMap<Thing> constructor:
Id(t => t.ID).Column("ThingID");
Map(t => t.SomeSimpleProp);
References(t => t.Type).Column("ThingTypeID");
References(t => t.OtherReference).Column("OtherReferenceID");
// In ThingTypeMap : ClassMap<ThingType> constructor:
Id(t => t.ID).Column("ThingTypeID");
Map(t => t.Name);
As I said, OtherReference is updated correctly while Type is not. They are mapped identically, so I don't see how this could be a mapping error.
You should specify <many-to-one .... cascade="save-update"/> in order to update references.

Setting CustomSqlType on References

I have a situation where my primary key is a char(2) in SqlServer 2008, and I want to reference it in a one-to-many relationship, but the ManyToOneBuilder (which is returned by ClassMap<>.References()) doesn't have a CustomSqlType() method. Specifically:
public class State
{
// state FIPS code is 2 characters
public virtual string StateCode { get; set; }
public virtual ICollection<County> { get; set; }
}
public class County
{
// state-county FIPS code is 5 characters
public virtual string StateCountyCode { get; set; }
public virtual State State { get; set; }
}
public class StateMap : ClassMap<State>
{
public StateMap()
{
Id(e => e.StateCode).CustomSqlType("char(2)").GeneratedBy.Assigned();
}
}
public class CountyMap : ClassMap<County>
{
public CountyMap()
{
Id(e => e.StateCountyCode).CustomSqlType("char(5)").GeneratedBy.Assigned();
References(e => e.State, "StateCode")
// Here's what I want to do, but can't because the method is not
// implemented on the class ManyToOneBuilder:
.CustomSqlType("char(2)");
}
}
Is there any way to accomplish this without modifying the ManyToOneBuilder? Is there a way to automatically map the FK (i.e. County.StateCode) to the correct type? It's trivial to add CustomSqlType to ManyToOneBuilder, but is that the right thing to do?
Keep your mapping definition as is, add your "State" column definition with
.CustomSqlType("char(2)")
and set for this column Insert=false and update=false.
I've the same problem and in AutoMapping I use this code:
mapping.Map(x => x.IdUniArticolo)
.CustomSqlType("varchar(50)")
.Not.Insert().Not.Update();
mapping.References(x => x.Articolo)
.Column("IdUniArticolo").PropertyRef("IdUniArticolo");
Keep in mind that if NHibernate itself doesn't support it, then Fluent NHibernate can't, and I don't NHibernate supports the scenario you have. I had a similar problem in that I had a 2 column composite key on a table and on one of the fields, I wanted to use an enumerated type which had a custom IUserType to translate it to its appropriate code value in the DB. Couldn't do it, so I was stuck keeping the property of the string type rather than the enumerated type.

NHibernate add unmapped column in interceptor

I'm trying to save a mapped entity using NHibernate but my insert to the database fails because the underlying table has a column that does not allow nulls and IS NOT mapped in my domain object. The reason it isn't mapped is because the column in question supports a legacy application and has no relevance to my application - so I'd like to not pollute my entity with the legacy property.
I know I could use a private field inside my class - but this still feels nasty to me. I've read that I can use an NHibernate interceptor and override the OnSave() method to add in the new column right before my entity is saved. This is proving difficult since I can't work out how to add an instance of Nhibernate.type.IType to the types parameter of my interceptor's OnSave.
My Entity roughly looks like this:
public class Client
{
public virtual int Id { get; set; }
public virtual int ParentId { get; set; }
public virtual string Name { get; set; }
public virtual string Phone { get; set; }
public virtual string Email { get; set; }
public virtual string Url { get; set; }
}
And my interceptor
public class ClientInterceptor : EmptyInterceptor
{
public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
{
if (entity is Client)
{
/*
manually add the COM_HOLD column to the Client entity
*/
List<string> pn_list = propertyNames.ToList();
pn_list.Add("COM_HOLD");
propertyNames = pn_list.ToArray();
List<Object> _state = state.ToList();
_state.Add(false);
state = _state.ToArray();
//somehow add an IType to types param ??
}
return base.OnSave(entity, id, state, propertyNames, types);
}
}
Does anyone have any ideas on how to do this properly?
I can't say for sure since I've never actually done this (like Stefan, I also prefer to just add a private property), but can you just add a NHibernate.Type.BooleanType to the types array?
List<IType> typeList = types.ToList();
typeList.Add(new BooleanType());
types = typesList.ToArray();
EDIT
Yes, it looks like you are right; the types have an internal constructor. I did some digging and found TypeFactory:
Applications should use static
methods and constants on
NHibernate.NHibernateUtil if the
default IType is good enough. For example, the TypeFactory should only
be used when the String needs to have a length of 300 instead of 255. At this point
NHibernate.String does not get you thecorrect IType. Instead use TypeFactory.GetString(300) and keep a
local variable that holds a reference to the IType.
So it looks like what you want is NHibernateUtil:
Provides access to the full range of
NHibernate built-in types. IType
instances may be used to bind values
to query parameters. Also a factory
for new Blobs and Clobs.
typeList.Add(NHibernateUtil.Boolean);
Personally I wouldn't do it so complicated. I would add the private property and assign it a default value - finished. You could also consider a default value in the database, then you don't need to do anything else.
private virtual bool COM_HOLD
{
get { return false; }
set { /* make NH happy */ }
}
Before writing a interceptor for that I would consider to write a database trigger. Because with the Interceptor you are "polluting" your data access layer. It could make it unstable and you could have strange problems.