views:

297

answers:

1

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

+3  A: 

What you are seeking to do will not work with LINQ to SQL. To use inheritance with LINQ to SQL, you have to make use of the [InheritanceMapping] attribute on your base class. Let's say you have a base class called Vehicle and a sub-class called Motorcycle:

[InheritanceMapping(Type = typeof(Motorcycle), IsDefault = true, Code = 1)]
[Table]
public class Vehicle
{
    [Column]
    pubic string Make { get; set; }

    [Column]
    pubic string Model { get; set; }

    [Column(IsDiscriminator = true, Name="VehicleTypeId")]
    public VehicleType VehicleType { get; set; }
}

public class Motorcycle : Vehicle
{
    // implementation here
}

In order to make this inheritance work in LINQ to SQL, you have to apply the [InheritanceMapping] to the base class and you also have to have a discriminator column (e.g., VehicleType in the above example). Notice the Code in the InheritanceMapping is "1" - that means if the VehicleType from the database is "1" then it'll create the Motorcycle sub-class. You apply one [InheritanceMapping] attribute on the base class for each sub-class you're supporting.

From a purist standpoint, this is a violation of OO because the base class knows about it's sub-classes. That bit of weirdness typically puts people off a little about how LINQ to SQL implements inheritance. But there you have it.

Update This works:

public abstract class BaseEntity<T, K> : IBaseEntity<K> where T : class, IBaseEntity<K>
{
    public abstract K Id { get; set; }

    public static Table<T> Table
    {
        get { return 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));
        context.SubmitChanges();
    }
}

Notice the difference is that I don't have any [Column] attribute on the Id property. Also notice I made it abstract. The implementing class looks like this:

[Table(Name = "dbo.Contacts")]
public class Contact : BaseEntity<Contact, int>
{
    [Column]
    public override int Id { get; set; }
    [Column]
    public string FirstName { get; set; }
    [Column]
    public string LastName { get; set; }
}

Notice the Id property in this class does have a [Column] attribute and I'm overriding the abstract propety. So I verified that works.

Having said that, there are a couple of reasons why I question your current design. First you've got your data access methods as part of your entity and many people (including myself) consider this a violation of Separation of Concerns. You could introduce the Repository pattern here and have a repository for each entity - make that repository generic based on the type and key. The other thing that is weird about the above approach is that the BaseEntity has an Id property and the sub-class (in my example the Contact class) also has a property of Id (to make Linq To Sql happy). Had to make the Id property in the base class abstract and then override it in the implementor. This violates DRY because I'll have to do this for each entity. But this is another thing that is the result of hoops you have to jump through to make LINQ to SQL happy. But it will work! :)

Steve Michelotti
ugh, then why does it work when I hardcode K as Guid, but doesn't when I try to implement K as a generic type?
Nico
Can you post the example code of how you have your entities set up currently?
Steve Michelotti
yup, just did..
Nico
I notice the version that works does not have the [Column] attribute on the Id property but the version that does not work, does have it. What behavior do you see when you add the Column attribute to the Guid version that works?
Steve Michelotti
The version that doesn't work is identical to the one that does, except it hasn't Guid hardcoded but as the generic type K
Nico
@Nico - Have a look at the update above. There's your answer.
Steve Michelotti