Plugin with data access

时间:2023-03-09 23:01:47
Plugin with data access

In this tutorial I'll be using the nopCommerce plugin architecture to implement a product view tracker.

We will start coding with the data access layer, move on to the service layer, and finally end on dependency injection.

Getting started

Create a new class library project "Nop.Plugin.Other.ProductViewTracker"

Add the following folders and decription.txt file.

Plugin with data access

Description.txt

Group: Other
FriendlyName: ProductViewTracker
SystemName: Other.ProtudctViewTracker
Version: 1.00
SupportedVersions: 3.20
Author: nopCommerce team
DisplayOrder: 1
FileName: Nop.Plugin.Other.ProductViewTracker.dll

Also add the following references and set their "Copy Local" property to "False":

  • Nop.Core.dll
  • Nop.Data.dll
  • Nop.Services.dll
  • Nop.Web.Framework.dll
  • EntityFramework.dll
  • System.Data.Entity.dll
  • System.Web.dll
  • System.Web.Mvc.dll
  • Autofac.dll
  • Autofac.Configuration.dll
  • Autofac.Integration.Mvc.dll

The Data Access Layer

Inside of the "domain" namespace we're going to create a public class named TrackingRecord. This class extends BaseEntity, but it is otherwise a very boring file. Something to remember is that all properties are marked as virtual and it isn't just for fun. Virtual properties are required on database entities because of how Entity Framework instantiates and tracks classes. One other thing to note is that we do not have navigation properties (relational properties), and I'll cover those in more detail later.

namespace Nop.Plugin.Other.ProductViewTracker.Domain
{
public class TrackingRecord : BaseEntity
{
public virtual int ProductId { get; set; }
public virtual string ProductName { get; set; }
public virtual int CustomerId { get; set; }
public virtual string IpAddress { get; set; }
public virtual bool IsRegistered { get; set; }
}
}

The next class to create is the Entity Framework mapping class. Inside of the mapping class we map the columns, table relationships, and the database table.

namespace Nop.Plugin.Other.ProductViewTracker.Data
{
public class TrackingRecordMap : EntityTypeConfiguration<TrackingRecord>
{
public TrackingRecordMap()
{
ToTable("ProductViewTracking"); //Map the primary key
HasKey(m => m.Id);
//Map the additional properties
Property(m => m.ProductId);
//Avoiding truncation/failure
//so we set the same max length used in the product tame
Property(m => m.ProductName).HasMaxLength();
Property(m => m.IpAddress);
Property(m => m.CustomerId);
Property(m => m.IsRegistered);
}
}
}