This is what I have so far
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
namespace Firelight.Business
{
public interface IBaseEntity<K>
{
K Id { get; }
}
/// <summary>
/// Base business database connection object, primary key is int
/// </summary>
/// <typeparam name="T">Table name</typeparam>
public abstract class BaseEntity<T> : BaseEntity<T, Guid> where T : class, IBaseEntity<Guid>
{
}
/// <summary>
/// Base business database connection object
/// </summary>
/// <typeparam name="T">Table name</typeparam>
/// <typeparam name="K">Primary key type</typeparam>
public abstract class BaseEntity<T,K> : IBaseEntity<K> where T : class, IBaseEntity<K>
{
// Avoids having to declare IBaseConnection at partial class level
[Column(Name = "Id", CanBeNull = false, IsPrimaryKey = true, IsDbGenerated = true)]
public K Id { get; set; } // { return default(K); }
public static Table<T> Table
{
get { return LinqUtil.Context.GetTable<T>(); }
}
public static T SearchById(K id)
{
return Table.Single<T>(t => t.Id.Equals(id));
}
public static void DeleteById(K id)
{
Table.DeleteOnSubmit(SearchById(id));
LinqUtil.Context.SubmitChanges();
}
}
}
My problem is that mapping doesn't work:
Data member 'System.Guid [or System.Int32] Id' of type 'X' is not part of the mapping for type 'X'. Is the member above the root of an inheritance hierarchy?
Before trying to map the attributes, I got this instead:
Could not find key member 'Id' of key 'Id' on type 'X'. The key may be wrong or the field or property on 'X' has changed names.
I tried changing K to Guid and it works, but why? I don't see how generic-typing is an issue here
I'm not entirely sure that I actually needed the Interface either, I don't really remember why I added it.
So, the question would be: How can I make a class like this work? I want it so I can access a commonly named PK (Id), which always has the type K [which is Guid or Int32], and refactor basic functions like select and delete by Id
Thanks!
EDIT:
this works
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
namespace Firelight.Business
{
public interface IBaseEntity<K>
{
K Id { get; set; }
}
/// <summary>
/// Base business database connection object
/// </summary>
/// <typeparam name="T">Table name</typeparam>
public abstract class BaseEntity<T> : IBaseEntity<Guid> where T : class, IBaseEntity<Guid>
{
// Avoids having to declare IBaseConnection at partial class level
public Guid Id { get; set; }
public static Table<T> Table
{
get { return LinqUtil.Context.GetTable<T>(); }
}
public static T SearchById(Guid id)
{
return Table.Single<T>(t => t.Id.Equals(id));
}
public static void DeleteById(Guid id)
{
Table.DeleteOnSubmit(SearchById(id));
LinqUtil.Context.SubmitChanges();
}
}
}
What I want would be basically the same, replacing Guid with K and making the class BaseEntity (so I can use the same class for Int32 and Guid PKs