NPoco
NPoco copied to clipboard
Cannot get foreign reference with composite primary keys to work
The following minimal example program produces a InvalidOperationException
exception:
using NPoco;
using System;
namespace NPocoTest
{
class Program
{
static void Main(string[] args)
{
using (var db = new NPoco.Database("<your connection string>", DatabaseType.MySQL, MySql.Data.MySqlClient.MySqlClientFactory.Instance))
{
var productInstances = db.Query<ProductInstance>().Include(pi => pi.SelectedFeatureSet).ToList();
}
}
}
[TableName("product_instance")]
[PrimaryKey("product_id,product_instance_id", AutoIncrement = false)]
public class ProductInstance
{
[Column("product_id")]
public Guid ProductId { get; set; }
[Column("product_instance_id")]
public Guid ProductInstanceId { get; set; }
[Column("selected_feature_set_id")]
public Guid? SelectedFeatureSetId { get; set; }
[Reference(ReferenceType.Foreign, ColumnName = "product_id,selected_feature_set_id", ReferenceMemberName = "ProductId,FeatureSetId")]
public FeatureSet SelectedFeatureSet { get; set; }
}
[TableName("feature_set")]
[PrimaryKey("product_id,feature_set_id", AutoIncrement = false)]
public class FeatureSet
{
[Column("product_id")]
public Guid ProductId { get; set; }
[Column("feature_set_id")]
public Guid FeatureSetId { get; set; }
}
}
Is there a mistake in my Reference attribute, or is there a bug in NPoco?
Here's the full stack trace:
Sequence contains no matching element
at System.Linq.ThrowHelper.ThrowNoMatchException()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at NPoco.Linq.ComplexSqlBuilder`1.GetJoinExpressions(Expression expression, String tableAlias, JoinType joinType)
at NPoco.Linq.AsyncQueryProvider`1.QueryProviderWithIncludes(Expression expression, String tableAlias, JoinType joinType)
at NPoco.Linq.AsyncQueryProvider`1.Include[T2](Expression`1 expression, JoinType joinType)
at NPoco.Linq.QueryProvider`1.Include[T2](Expression`1 expression, JoinType joinType)
at NPocoTest.Program.Main(String[] args) in C:\Robert\Temp\NPocoTest\Program.cs:line 12
Ok I did dig a little bit into the NPoco source code. It looks like ComplexSqlBuilder.GetJoinExpressions
does not support (comma separated) composite keys.
It looks like it would be relatively easy to enhance the onSql
expression to compare multiple columns. So I could probably provide a pull request for that. But there is also the other part of GetJoinExpressions
which populates a JoinData
object, and I don't understand the bigger context of that and whether that object would also need to be aware of the composite key. @schotime can you advise?
I cant get foreign keys to work at all. Keep getting Sequence contains no matching element
.