0 people following this project (follow)

Project Description
Base entity class for LINQ2SQL. Provides automatic CRUD methods for LINQ entities.

About

This project is based upon http://www.codeplex.com/LINQ2SQLEB

Implementation

Follow the instructions below to implement EntityBase with your LINQ2SQL classes.

1. Your DBML's Serialization Mode must be set to Unidirectional
2. Entities must contain a Timestamp property which is a SQL timestamp column
3. Entity properties must be set to Update Check: Never
4. Implement a base class for each DataContext required

To implement on your DataContext, take the following example of the base class for "CoreDataContext.dbml" entities and substitute Core for your DataContext name:

public abstract class CoreEntity<TEntityType, TKeyType>
: OpenQuarters.EntityBase.EntityBase<TEntityType, TKeyType, CoreDataContext>
where TEntityType : OpenQuarters.EntityBase.EntityBase<TEntityType, TKeyType, CoreDataContext>
{}

5. Utilise each entity's partial class to inherit from the base class

For each entity in the DataContext that you want to use with EntityBase, implement a partial class of the LINQ2SQL-generated class as in this example of the EventLog class, whose primary key (EventId) is a long (bigint):

public partial class EventLog: CoreEntity<EventLog, long>
{
public override System.Linq.Expressions.Expression<Func<*EventLog*, long>> GetIDSelector(string ID)
{
return e => e.*Event*Id == ID;
}

public override string GetKey(EventLog Entity)
{
return Entity.*Event*Id;
}
}

Here is an example of the Language class, whose primary key is a string. In the case of string keys, you will need to implement IsNew as shown below.

public partial class Language : CoreEntity<Language, string>
{
public override System.Linq.Expressions.Expression<Func<*Language*, bool>> GetIDSelector(string ID)
{
return e => e.*Language*Id == ID;
}

public override string GetKey(Language Entity)
{
return Entity.*Language*Id;
}

public override bool IsNew(Language Entity)
{
return Table.FirstOrDefault(e => e.*Language*Id == Entity.*Language*Id) == null;
}
}

Creating and Saving Entities

Creating new entities is as simple as:

Language language = new Language()
{
LanguageId = "en",
IsDefault = true,
Title = "English"
}.Save();

or

Language language = new Language();
LanguageId = "en",
IsDefault = true,
Title = "English"
language = language.Save();

Last edited May 9 2009 at 8:51 PM by tags2k, version 10