I’m sure you’re all tired of me blogging about L2S, but I still like it. It’s just so simple and easy to use. Obviously with .net 4.0, the big issues with L2S seem to be resolved. Alongside l2sprof, LINQ to SQL can be very effective. Anyhow, I thought I’d share a simple generic repository I made.
Here's how you'd use the repository. Basically, you just pass in the DataContext you want to use and then call the method needed. As usual, please let me know if you see any improvements that can be made or if you have any questions.Tuesday, April 03, 2012
Monday, June 14, 2010
jQuery AJAX with ASP.NET Web Forms & Sitefinity
My team and I are working with Sitefinity to create our new portal. Well, since Sitefinity doesn’t currently support MVC, we’re having to use the “good” ole web forms. Sitefinity is a really nice CMS and allows for full customization and we’re still learning how to handle the custom user controls. So…this is how we’re doing it right now.
We wanted to allow our users to add quick links to their home screen, so that’s the sample I’m going to use. First, I created two projects, one called UserControlSample.Core (class library) and the other called UserControlSample.UI (a blank Web project).
I started with the domain model, which looks like this:
public class QuickLink
{
public Guid Id { get; set; }
public string DisplayName { get; set; }
public string URL { get; set; }
public string UserId { get; set; }
public string BuildHyperlink()
{
return string.Format("<a href=\"{0}\" title=\"{1}\">{1}</a>", URL, DisplayName);
}
}
Generally, I wouldn’t put the UserId in this class, but for this example it just made it easier.
After the domain model, I added the repository interface, which is this:
public interface IQuickLinkRepository
{
QuickLink[] GetAllBy(string userId);
void Add(QuickLink quickLink);
void Delete(Guid quickLinkId);
}
You can download the project to see the implementation of the interface. I used L2S and again, you can download the project to see the implementation. Alrighty, so let’s get to the real code that you can use.
I added a user control, which looks like this:
<div id="quicklinks">
<div>
<div class="loader" id="loading" style="display: none"></div>
<asp:Repeater ID="rQuickLinks" runat="server">
<HeaderTemplate><h3>Quick Links</h3><ul></HeaderTemplate>
<ItemTemplate><li id="li<%# ((QuickLink)Container.DataItem).Id %>"><img src="/_a/i/ico-delete.png" width="16" height="16" alt="Delete <%# ((QuickLink)Container.DataItem).DisplayName %>" id="<%# ((QuickLink)Container.DataItem).Id %>" /><%#((QuickLink)Container.DataItem).BuildHyperlink() %></li></ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
<a href="#" id="addQuickLink" title="Add Quick Link">Add Quick Link</a>
</div>
<div style="display: none">
<fieldset>
<legend>Add Quick Link</legend>
<p><label for="<%=tbDisplayName.ClientID %>" title="Display Name:">Display Name:</label><br />
<asp:TextBox ID="tbDisplayName" runat="server" /> <asp:RequiredFieldValidator ValidationGroup="addQuickLink" ControlToValidate="tbDisplayName" Display="Dynamic" ID="rv1" SetFocusOnError="true" runat="server">*</asp:RequiredFieldValidator></p>
<p><label for="<%=tbURL.ClientID %>" title="Website Address:">Website Address:</label><br />
<asp:TextBox ID="tbURL" runat="server" /> <asp:RequiredFieldValidator ValidationGroup="addQuickLink" ControlToValidate="tbURL" Display="Dynamic" ID="rv2" SetFocusOnError="true" runat="server">*</asp:RequiredFieldValidator> <asp:RegularExpressionValidator ControlToValidate="tbURL" Display="Dynamic" ID="re1" runat="server" SetFocusOnError="true" ValidationGroup="addQuickLink" ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?">*</asp:RegularExpressionValidator></p>
</fieldset>
<asp:Button ID="bSubmit" runat="server" CausesValidation="true" Text="Add Quick Link" ValidationGroup="addQuickLink" OnClick="AddQuickLink" /> <a href="#" title="Cancel Quick Link Addition" id="cancelAddQuickLink">Cancel</a>
</div>
</div>
That looks really messy, but that’s web forms for ya :D
Here’s the interesting part, instead of having a code-behind and inheriting from a partial, we added a class to the Core.UI.Controls called QuickLinksControl. Here’s the code:
public class QuickLinksControl : BaseControl
{
private IQuickLinkRepository _repository;
protected void Page_Load(object sender, EventArgs e)
{
_repository = DependencyResolution.DependencyRegistrar.Resolve<IQuickLinkRepository>();
if (Request.Form["QLID"] != null)
DeleteQuickLink(new Guid(Request.Form["QLID"]));
if(!Page.IsPostBack)
LoadQuickLinks();
}
private void DeleteQuickLink(Guid quickLinkId)
{
_repository.Delete(quickLinkId);
Response.Write(quickLinkId);
Response.End();
}
protected void AddQuickLink(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
var tbDisplayName = (TextBox)Page.FindControl("tbDisplayName");
var tbURL = (TextBox)Page.FindControl("tbURL");
var button = (Button) sender;
var quickLink = new QuickLink {DisplayName = tbDisplayName.Text, URL = tbURL.Text, UserId = button.CommandArgument};
_repository.Add(quickLink);
tbDisplayName.Text = "";
tbURL.Text = "";
LoadQuickLinks();
}
private void LoadQuickLinks()
{
var rQuickLinks = (Repeater) FindControl("rQuickLinks");
rQuickLinks.DataSource = _repository.GetAllBy(Page.User.Identity.Name);
rQuickLinks.DataBind();
}
}
The interesting parts…
- DeleteQuickLink() is checked in the Page_Load. We’re doing this here for an AJAX call from the ascx file. We’re probably going to add some type of validation token to the if statement as well. We also might create some type of AJAX call handler instead of throwing them in the page_load, but it works for now.
- In the DeleteQuickLink method, we’re calling Response.Write(quickLinkId) and Response.End(). This is used for the AJAX call too to return the guid sent. There’s probably a better way, but so far this is working.
- In the AddQuickLink, you’ll notice that we’re having to find the controls because it’s not a partial and doesn’t know anything about the ascx page. This part kinda stinks, but it’s not too bad.
Here are the AJAX calls from the ascx page:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#addQuickLink,#cancelAddQuickLink").click(function() {
$("div#quicklinks div").toggle();
});
$("#loading").ajaxStart(function() {
$(this).show().text("Deleting...");
}).ajaxStop(function() {
$(this).hide().text("");
});
$('#quicklinks ul li img').click(function() {
if (!confirm('Are you sure you want to delete?'))
return;
$.post(window.location.href, { QLID: $(this).attr('id') }, function(data) {
$("#li" + data).remove();
});
});
});
</script>
I’ve never used the ajaxStart or ajaxStop before, but they’re pretty cool features. I also wanted to note that I started using StructureMap 2.6.1 and I’m liking it. It’s a pretty big difference from the last blog post on StructureMap. Now the ForRequestedType<> in the registry looks like this:
For<IQuickLinkRepository>()
.Use<QuickLinkRepository>()
.Ctor<string>("connstring")
.Is(@"Data Source=.\SQLEXPRESS;AttachDbFilename=""..\LearnerSample.mdf"";Integrated Security=True;User Instance=True");
Here’s the finished product:
So, any thoughts or ideas on what we’re doing? I’d appreciate any advice or comments. It’s probably easier to understand by downloading the sample code.
Thanks for reading!
Friday, May 07, 2010
Building a L2S Expression with .NET 3.5
I recently wanted to reduce some code redundancy by extracting out some code. We had a few helper methods that got results by specific fields.
For example:
public IList<HelpRequest> GetByLastName(string lastName)
{
return _dc.HelpRequest
.Where(x=>x.LastName.StartsWith(lastName))
.OrderBy(y => y.RequestDate).ToList();
}
public IList<HelpRequest> GetByFirstName(string firstName)
{
return _dc.HelpRequests
.Where(x => x.FirstName.StartsWith(firstName))
.OrderBy(y => y.RequestDate).ToList();
}
So obviously there is some redundant code here that we can get rid of and we did. First we created another helper method like this:
public IList<HelpRequest> GetByLastName(string search)
{
return GetBy(x => x.LastName.StartsWith(search));
}
public IList<HelpRequest> GetByFirstName(string search)
{
return GetBy(x => x.FirstName.StartsWith(search));
}
private IList<HelpRequest> GetBy(Expression<Func<HelpRequest, bool>> func)
{
return _dc.HelpRequests
.Where(func)
.OrderBy(y => y.RequestDate).ToList();
}
So that got rid of some of the duplication, but not all of it. We’re still doing a StartsWith in the helper and I didn’t want to do that logic there. So…now we have this and this took a long time to figure out…so I’m sure there is a better way because I basically got this working and stopped. Anyhow, here is the latest version, which has more lines of code, but less redundancy. I’m not sure which is better at this point…I’m thinking maybe the first refactoring, but this one is cool too and more flexible I think.
public IList<HelpRequest> GetByLastName(string search)
{
return GetBy(LastName => search);
}
public IList<HelpRequest> GetByFirstName(string search)
{
return GetBy(FirstName => search);
}
private IList<HelpRequest> GetBy(Func<string, string> func)
{
return _dc.HelpRequests
.Where(func.StartsWith<HelpRequest>())
.OrderBy(y => y.RequestDate)
.ToList();
}
This one goes along with an extension method that looks like this: (Code below OUTDATED as of 5/9/2010 SEE BELOW)
public static Func<T, bool> StartsWith<T>(this Func<string, string> func)
{
var searchBy = func.Method.GetParameters()[0].Name;
var search = Expression.Constant(func(null), typeof(string));
var searchByParam = Expression.Parameter(typeof(T), searchBy);
var searchByProp = Expression.Property(searchByParam, searchBy);
var ignoreCase = Expression.Constant(StringComparison.CurrentCultureIgnoreCase);
var methodInfo = typeof(string).GetMethod("StartsWith", new[]{typeof(string), typeof(StringComparison)});
var containsExpression = Expression.Call(searchByProp, methodInfo, search, ignoreCase);
return Expression.Lambda<Func<T, bool>>(containsExpression, searchByParam).Compile();
}
So, as you can see this little extension method is kinda loaded down. I’m hoping there are some shortcuts to writing these expressions that I don’t know about…but I haven’t found any good examples. I browsed Google for a while and StackOverflow. I even submitted a question…I had one response, but it wasn’t exactly what I was looking for as you can see here. Anyhow, let’s go through this code.
First let’s talk about the GetByLastName & GetByFirstName methods…they’re REALLY simple now, but with one pretty big caveat I think. That caveat is that the property name isn’t strongly typed. If you follow my blog at all, you know I’m a BIG fan of strongly typed things, but I haven’t found a better way in this instance. So, LastName & FirstName are properties on my HelpRequest object. I used this same method in the “Fun with Lambdas & HtmlHelpers” post. Alrighty, let’s keep going…so the GetBy(Func<string, string>) simply calls the func.StartsWith extension method and returns my IList…now to the meat of this post.
The extension method StartsWith<T> could be put into like 3 lines, but it’s way less readable when you do that…I basically set a variable for every different type of Expression object to keep it a bit readable. So the first thing I do is get my search by, which is my property name. On the next line, I create a constant, which is the right-side of the func passed in. Next on the list is the search by parameter, which sets the type to HelpRequest with the name of searchby (in this case, FirstName or LastName). After that I set an Expression.Property for the searchBy and then I set another constant for the ignorecase that I’m going to pass into StartsWith in a bit.
Now, I find the method “StartsWith” on a string and setup the parameter definitions of what I want to pass in. In this case, a string and a StringComparison. After this, I call the startsWith on the search property with the search and ignoreCase parameters.
Finally, I return the lambda expression that is required for my Where on my LINQ to SQL statement. I also found that you have to call the Compile in order for it to work. What I do like about this extension method is that I can now use it for all my searches. Of course I’m going to continue testing it and verifying that there’s not a better way, but for now, I think it’ll work.
Please let me know if you have any suggestions or comments.
Thanks for reading!
UPDATE: 5/9/2010
So thanks to Brad commenting on using Ants or SQL Profiler, I did a little more investigating on the code above. Basically what was happening was this:
SELECT [t0].[FirstName], [t0].[LastName]
FROM [hd].[HelpRequest] AS [t0]
So, I made some adjustments to the static StartsWith<T> method and now it looks like this:
private static Expression<Func<T, bool>> StartsWith<T>(Func<string, string> func)
{
var searchBy = func.Method.GetParameters()[0].Name;
var search = Expression.Constant(func(null), typeof(string));
var searchByParam = Expression.Parameter(typeof(T), searchBy);
var searchByExp = Expression.Property(searchByParam, searchBy);
//var ignoreCase = Expression.Constant(StringComparison.CurrentCultureIgnoreCase);
var methodInfo = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });//, typeof(StringComparison)});
var containsExpression = Expression.Call(searchByExp, methodInfo, search);//, ignoreCase);
return Expression.Lambda<Func<T, bool>>(containsExpression, searchByParam);//.Compile();
}
First thing to note is the return type has been changed from Func<T, bool> to Expression<Func<T, bool>>. This allows us to do away with the Compile() at the bottom of the method. I was also able to do away with the ignoreCase and StringComparison stuff because it’s converted to SQL and in this case we’re not caring about case-sensitvitity. So now my SQL looks like this:
exec sp_executesql N'SELECT [t0].[FirstName], [t0].[LastName]
FROM [hd].[HelpRequest] AS [t0]
WHERE [t0].[FirstName] LIKE @p0',N'@p0 varchar(7)',@p0='deran %'
So, this is a good thing. Thank you Brad! Please let me know if you see anything else that could cause a problem.
Thursday, January 28, 2010
Linq to Sql Generic Repository with AutoMapper
We, my teammates and I, have been playing with creating a generic repository for Linq to Sql using AutoMapper. We haven’t used it in production or anything, but I figured I’d blog about it and see if anyone has any comments about it. It’s fun just to toy around sometimes.
A couple of posts ago, I blogged about Func<> and that’s going to play an important part in what I’m about to show you. So basically we started off coding what we would do without generics and then converted that into a generic method. The ending interface looks like this:
public interface ILinq2SqlRepository<TDataContext, TDomainModel, TLinqModel>
where TDataContext : DataContext
{
IList<TDomainModel> GetAll(Func<TDataContext, IQueryable<TLinqModel>> func);
TDomainModel GetById(Func<TDataContext, TLinqModel> func);
void Save(TDomainModel model, Func<TDataContext, TLinqModel> func);
}
So there is the GetAll and the GetById methods. I’m also working on the Save, but it’s a little more tricky because I believe there’s a bug in Linq to Sql Attach(entity, original) when the primary key is a Guid, but that’s just me :) My Save method right now keeps returning a cannot insert duplicate key error and I’ve Googled it, but to no avail. I’m also not sure how to handle the using(DataContext)…just know it’s a work in progress! Anyhow…
The implementation looks like this:
public class Linq2SqlRepository<TDataContext, TDomainModel, TLinqModel>
: ILinq2SqlRepository<TDataContext, TDomainModel, TLinqModel>
where TDataContext: DataContext
{
private readonly TDataContext DataContext;
public Linq2SqlRepository(TDataContext dataContext)
{
DataContext = dataContext;
}
public IList<TDomainModel> GetAll(Func<TDataContext, IQueryable<TLinqModel>> func)
{
var list = Mapper.Map<TLinqModel[], TDomainModel[]>(func.Invoke(DataContext).ToArray());
return list.ToList();
}
public TDomainModel GetById(Func<TDataContext, TLinqModel> func)
{
return Mapper.Map<TLinqModel, TDomainModel>(func.Invoke(DataContext));
}
public void Save(TDomainModel model, Func<TDataContext, TLinqModel> func)
{
using (DataContext)
{
var original = func.Invoke(DataContext);
var entity = Mapper.Map<TDomainModel, TLinqModel>(model);
DataContext.GetTable(typeof(TLinqModel)).Attach(entity, original);
DataContext.SubmitChanges();
}
}
}
Well here’s the base implementation and it looks a lot easier if you have a good understanding of .Net generics. You can see the common AutoMapper Mapper.Map<> method in there, which is what we’re using to do the left to right mapping and basically we’re just passing in simple Linq commands. So we still have to do our AutoMapper configuration, but my hope is that maybe this post will strike up a good idea in someone else’s head…hopefully!
I thought it’d work best to implement this into a repository by just setting it as a private field like this:
public class SampleRepository : IRepository<DomainPerson>
{
private readonly ILinq2SqlRepository<SampleDataContext, DomainPerson, DataPerson> _repository;
public SampleRepository(string connstring)
{
_repository = new Linq2SqlRepository<SampleDataContext, DomainPerson, DataPerson>(
new SampleDataContext(connstring));
}
public IList<DomainPerson> GetAll()
{
return _repository.GetAll(x => x.DataPeople);
}
public DomainPerson GetById(Guid id)
{
return _repository.GetById(x => x.DataPeople.SingleOrDefault(y => y.Id == personId));
}
public void Save(DomainPerson person)
{
_repository.Save(person, x => x.DataPeople.SingleOrDefault(y => y.Id == person.Id));
}
}
I went the inheritance route and didn’t really care for it, mainly because it was much uglier in the implementation. So you’ll notice this inherits from a generic IRepository, which could’ve been IDomainPersonRepository that inherits from the generic or was just a plain ole repository. Anyhow, it looks like this:
public interface IRepository<T>
{
IList<T> GetAll();
T GetById(Guid id);
void Save(T model);
}
I wanted to show prettier things in the public side of the API like GetById with just Guid instead of pass me an ugly lambda :) (Even though I love the lambdas, a lot of devs don’t care for them) So the users of this API would just reference the IRepository<T>, but I’d actually probably end up renaming to a friendlier name like this:
public interface IDomainPersonRepository : IRepository<DomainPerson> {}
Then I’d go ahead and inherit my SampleRepository from IDomainPersonRepository…I should really plan these posts out more than I do before typing them so the post is better structured. As I get more practice in, I’ll try to do that for you!
So that’s my thinking on some type of generic repository for Linq to Sql with AutoMapper. Please keep in mind that this was a fly by thing we came up with this afternoon and I thought it was pretty cool. It could definitely use more testing & refactoring!
Let me know if you have any thoughts, questions, or comments.
Thanks for reading!
Saturday, November 28, 2009
LINQ to SQL with AutoMapper
So I created a really simple domain model that looks like this:
After I created my domain model, I created a implementation project with a simple repository and a DBML file, which looks like this:
The repository code looks like this:
public class PhotoRepository : IDisposable
{
private readonly PhotosDataContext _dc;
public PhotoRepository()
{
Registry.AutoMapperRegistry.Configure();
_dc = new PhotosDataContext();
}
public List<Photo> GetAll()
{
return Mapper.Map<PhotoDataModel[], Photo[]>(_dc.PhotoDataModels.ToArray()).ToList();
}
public void Save(Photo photo)
{
Registry.AutoMapperRegistry.Configure();
using (var dc = new PhotosDataContext())
{
dc.PhotoDataModels.InsertOnSubmit(Mapper.Map<Photo, PhotoDataModel>(photo));
dc.SubmitChanges();
}
}
public void Dispose()
{
if (_dc != null)
_dc.Dispose();
}
}
So in the implementation project, I added my AutoMapper configuration. I setup two profiles one for the LINQtoSQL and then one to reverse it. Here's that code:
public class AutoMapperRegistry
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<LinqToSqlProfile>();
x.AddProfile<LinqToSqlReverseProfile>();
});
}
}
public class LinqToSqlProfile : Profile
{
protected override string ProfileName
{
get
{
return "LinqToSqlProfile";
}
}
protected override void Configure()
{
Mapper.CreateMap<PhotoDataModel, Photo>()
.ForMember(dest => dest.Photographer, opt => opt.MapFrom(src=>src.PhotographerDataModel));
Mapper.CreateMap<PhotographerDataModel, Photographer>();
}
}
public class LinqToSqlReverseProfile:Profile
{
protected override string ProfileName
{
get
{
return "LinqToSqlReverseProfile";
}
}
protected override void Configure()
{
Mapper.CreateMap<Photo, PhotoDataModel>()
.ForMember(dest => dest.PhotographerDataModel, opt => opt.MapFrom(src => src.Photographer));
Mapper.CreateMap<Photographer, PhotographerDataModel>();
}
}
You'll notice in my repository I call the configure method twice once in the constructor and again on the save. I didn't have to do it in the save, but the way I did the console app, it was required. I could've called it before calling the save, but I wanted it all in one place to make it a little easier to read...I think it is anyhow.
So in order to flatten out my domain model like Headspring seems to practice and I try to mimic everything they do because lets face it, they're the best software company in the world. At least that's my opinion. So here is my view model:
public class PhotoViewModel
{
public string Name { get; set; }
public string FileSize { get; set; }
public DateTime DateTaken { get; set; }
public string Description { get; set; }
public string PhotographerName { get; set; }
}
Here is my AutoMapper configuration for the UI project:
public class ViewProfile:Profile
{
protected override string ProfileName
{
get{ return "ViewProfile"; }
}
protected override void Configure()
{
Mapper.CreateMap<Core.Photo, PhotoViewModel>()
.ForMember(dest => dest.PhotographerName, opt => opt.MapFrom(src => src.Photographer.Name));
}
}
Here's the initialization:
public class AutoMapperRegistry
{
public static void Configure()
{
Mapper.Initialize(x => x.AddProfile<ViewProfile>());
}
}
Finally, here is my UI code that displays a list of the photographers and then saves a new one.
static void Main(string[] args)
{
var pr = new PhotoRepository();
var photos = pr.GetAll();
AutoMapperRegistry.Configure();
foreach (var p in photos)
{
var photo = Mapper.Map<Photo, PhotoViewModel>(p);
Console.WriteLine("Photographer: " + photo.PhotographerName);
}
Console.Read();
var p1 = new Photo();
p1.Id = Guid.NewGuid();
p1.Name = "Test Photo";
p1.Photographer.Id = Guid.NewGuid();
p1.Photographer.Name = "John Smith";
p1.DateTaken = DateTime.Now;
pr.Save(p1);
}
Download Source Here
Hopefully Jimmy reads this post and lets me know if there is anything messed up or anything that I'm not doing correctly with my mappings.
Wednesday, July 22, 2009
LINQ to SQL or NHibernate
So I’ve been trying to figure out which direction I wanted my team to go in as far as O/RMs go and I think I’ve decided. I’ve heard the only good things about Entity Framework are the portions taken from the LINQ to SQL team. Therefore, I spent some time playing with LINQ to SQL and definitely think it’s a great tool for quick and dirty projects. However, after spending a few days and actually using NHibernate in a major project…I love it. So far, we haven’t come across anything that it can’t do and after hearing some stories indirectly from Jeffrey Palermo I’m pretty sure we won’t. So on to the example.
The application I was needing to build was a simple information request form and I used LINQ to SQL first and wanted to plug in a NHibernate version later. Kind of like the Rob Conery & Jimmy Bogard challenge on the MVC Storefront.
Here’s my Core project: (Really small I know...needed something to get the point across)
I won’t go into all the details on the implementation, but the main thing I want to show is the difference in mapping and implementation of the repository. If you don’t know how to configure NHibernate, I recommend the NHibernate in Action book. As for LINQ to SQL, create a DBML and drag some tables over…DONE.
First I’ll show a few methods of IRequestRepository implemented with NHibernate and then the LINQ to SQL version.
public Core.Model.InformationRequest GetById(Guid id)
{
using (ISession session = NHibernateHelper.OpenSession())
return session.Get<Core.Model.InformationRequest>(id);
}
public IList<Core.Model.InformationRequest> GetAll()
{
using (ISession session = NHibernateHelper.OpenSession())
{
var records = session
.CreateCriteria(typeof(Core.Model.InformationRequest))
.List<Core.Model.InformationRequest>();
return records;
}
}
public IList<Core.Model.InformationRequest> GetAllCompleted()
{
using (ISession session = NHibernateHelper.OpenSession())
{
return session
.CreateQuery("from InformationRequest WHERE IsCompleted='true'")
.List<Core.Model.InformationRequest>();
}
}
Obviously I’m still learning NHibernate because we haven’t encapsulated anything or really figured out the best way to refactor it.public void Save(Core.Model.InformationRequest newRequest)
{
using (ISession session = NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(newRequest);
transaction.Commit();
}
}
Here is the implementation of the same methods using LINQ to SQL.
With LINQ to SQL, I used a few filters and some mapping, but I’ll show those once I’ve shown the mapping file for NHibernate.public Core.Model.InformationRequest GetById(Guid id)
{
return dc.GetById(id);
}
public IList<Core.Model.InformationRequest> GetAll()
{
return dc.GetAll()
.ToList();
}
public IList<Core.Model.InformationRequest> GetAllCompleted()
{
return dc.GetAll()
.WithCompletionStatus(true)
.ToList();
}public void Save(Core.Model.InformationRequest request)
{
using (var db = new OPIDataContext(_connstring))
{
var newrequest = RequestMap.GetDbRequestFrom(request);
db.InformationRequests.InsertOnSubmit(newrequest);
db.SubmitChanges();
}
}
With NHibernate, that’s it! Really easy once you know the syntax. Also, as a general rule, I like to write things from scratch when I’m learning so I fully understand what’s going on. So I won’t be using CodeSmith or some other similar tool.<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="TPIAR.Core.Model"
assembly="TPIAR.Core">
<class name="InformationRequest" table="[opi].[InformationRequest]">
<id name="Id" column="RequestId">
<generator class="guid.comb" />
</id>
<component class="Sample.Core.Model.Common.PersonName,Sample" name="Name">
<property name="FirstName"/>
<property name="LastName"/>
</component>
<property name="CompanyName" />
<component class="Sample.Core.Model.Common.Address,Sample" name="Address">
<property column="Address" name="StreetLine1"/>
<property name="City"/>
<property name="State"/>
<property name="PostalCode"/>
</component>
<property name="TelephoneNumber"/>
<property name="FaxNumber"/>
<property name="EmailAddress"/>
<property name="RequestSummary"/>
<property name="RequestDate"/>
<property name="CompletionDate"/>
<property name="IsCompleted"/>
</class>
</hibernate-mapping>
Now for LINQ to SQL:
Here is the filter I used:internal static InformationRequest GetById(this OPIDataContext dataContext, Guid Id)
{
var r = Enumerable.SingleOrDefault(dataContext.InformationRequests, x => x.RequestId == Id);
return new InformationRequest
{
Id = r.RequestId,
Name = new PersonName(r.FirstName, r.LastName),
CompanyName = r.CompanyName,
Address = new Address{City = r.City, PostalCode = r.PostalCode, State = r.State, StreetLine1 = r.Address},
TelephoneNumber = r.TelephoneNumber,
FaxNumber = r.FaxNumber,
EmailAddress = r.EmailAddress,
RequestSummary = r.RequestSummary,
RequestDate = r.RequestDate,
CompletionDate = r.CompletionDate,
IsCompleted = r.IsCompleted
};
}
internal static IQueryable<InformationRequest> GetAll(this OPIDataContext dataContext)
{
var requests = from r in dataContext.InformationRequests
select new InformationRequest
{
Id = r.RequestId,
Name = new PersonName(r.FirstName, r.LastName),
CompanyName = r.CompanyName,
Address =
new Address
{
City = r.City,
PostalCode = r.PostalCode,
State = r.State,
StreetLine1 = r.Address
},
TelephoneNumber = r.TelephoneNumber,
FaxNumber = r.FaxNumber,
EmailAddress = r.EmailAddress,
RequestSummary = r.RequestSummary,
RequestDate = r.RequestDate,
CompletionDate = r.CompletionDate,
IsCompleted = r.IsCompleted
};
return requests;
}
internal static DataAccess.InformationRequest GetDbRequestFrom(InformationRequest request)
{
var ir = new DataAccess.InformationRequest
{
RequestId = (request.Id == new Guid("99999999-9999-9999-9999-999999999999") ? Guid.NewGuid() : request.Id),
Address = request.Address.StreetLine1,
City = request.Address.City,
CompanyName = request.CompanyName,
CompletionDate = request.CompletionDate,
EmailAddress = request.EmailAddress,
FaxNumber = request.FaxNumber,
FirstName = request.Name.FirstName,
IsCompleted = request.IsCompleted,
LastName = request.Name.LastName,
PostalCode = request.Address.PostalCode,
RequestDate = request.RequestDate,
RequestSummary = request.RequestSummary,
State = request.Address.State,
TelephoneNumber = request.TelephoneNumber
};
return ir;
}
So there you go…LINQ to SQL & a NHibernate implementation that use exactly the same Core & UI. I also have a couple integration tests, which look like this:internal static IQueryable<InformationRequest> WithCompletionStatus(this IQueryable<InformationRequest> qry, bool status)
{
return qry
.Where(x => x.IsCompleted == status);
}
So I guess that’s about it. Please post comments or questions. I love feedback! Thanks![Test]
public void should_get_all_completed_using_linqtosql()
{
IRequestRepository rep = new SqlRequestRepository("connstring");
IList<InformationRequest> list = rep.GetAllCompleted();
Assert.AreEqual(2, list.Count);
}
[Test]
public void should_get_all_completed_using_nhibernate()
{
IRequestRepository rep = new NhRequestRepository();
IList<InformationRequest> list = rep.GetAllCompleted();
Assert.AreEqual(2, list.Count);
}
