Dotnet洋葱架构实践

实现数据层
在DomainLayer目录里,建一个Models目录。在Models目录下,建两个类:

BaseEntity.cs

public class BaseEntity
{
public int Id { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public bool IsActive { get; set; }
}
Customer.cs

public class Customer : BaseEntity
{
public string CustomerName { get; set; }
public string PurchasesProduct { get; set; }
public string PaymentType { get; set; }
}
两个类,Customer派生自BaseEntity。没什么特殊的含义,也是一个习惯。而且,后面到存储层写着方便。

后面,我们会用到Customer和BaseEntity实体类创建的数据表。为了让大家看的明白,我在这儿建一个目录

EntityMapper,在目录里写个表结构映射。

CustomerMap.cs

public class CustomerMap : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder builder)
{
builder.HasKey(x => x.Id)
.HasName(“pk_customerid”);

    builder.Property(x => x.Id).ValueGeneratedOnAdd()
        .HasColumnName("id")
            .HasColumnType("INT");
    builder.Property(x => x.CustomerName)
        .HasColumnName("customer_name")
            .HasColumnType("NVARCHAR(100)");
    builder.Property(x => x.PurchasesProduct)
        .HasColumnName("purchased_product")
            .HasColumnType("NVARCHAR(100)")
            .IsRequired();
    builder.Property(x => x.PaymentType)
        .HasColumnName("payment_type")
            .HasColumnType("NVARCHAR(50)")
            .IsRequired();
    builder.Property(x => x.CreatedDate)
        .HasColumnName("created_date")
            .HasColumnType("datetime");
    builder.Property(x => x.ModifiedDate)
        .HasColumnName("modified_date")
            .HasColumnType("datetime");
    builder.Property(x => x.IsActive)
        .HasColumnName("is_active")
            .HasColumnType("bit");
}

}
或者也可以自己创建一个表ef.Customer:

CREATE TABLE Customer (
id int NOT NULL AUTO_INCREMENT,
created_date datetime DEFAULT NULL,
customer_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
is_active bit(1) DEFAULT NULL,
modified_date datetime DEFAULT NULL,
payment_type varchar(50) DEFAULT NULL,
purchased_product varchar(100) DEFAULT NULL,
PRIMARY KEY (id) USING BTREE
)
3. 实现存储层
这个层,主要用来操作数据库。

先在Startup.cs中配置数据库引用:

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool(
options => options.UseMySql(
“server=192.168.0.241;user=root;password=xxxxxx;database=ef”,
new MySqlServerVersion(new Version(8, 0, 21)),
mysqlOptions =>
{
mysqlOptions.CharSetBehavior(CharSetBehavior.NeverAppend);
}
));
}
}
这儿偷个懒,连接串就直接写代码里了。正式做项目时,最好写在配置文件中。

在RepositoryLayer目录中建一个DataContext,里面用来放置相关数据库会话,和操作的实例:

ApplicationDbContext.cs

public partial class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new CustomerMap());

    base.OnModelCreating(modelBuilder);
}

}
再建个目录RespositoryPattern,用来存放数据库操作的类。按照注入的原则,会是两个文件,一个接口定义,一个实

现类:

IRepository.cs

public interface IRepository where T : BaseEntity
{
IEnumerable GetAll();
T Get(int Id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
void Remove(T entity);
void SaveChanges();
}
Repository.cs

public class Repository : IRepository where T : BaseEntity
{
private readonly ApplicationDbContext _applicationDbContext;
private DbSet entities;

public Repository(ApplicationDbContext applicationDbContext)
{
    _applicationDbContext = applicationDbContext;
    entities = _applicationDbContext.Set();
}

public void Delete(T entity)
{
    if (entity == null)
    {
        throw new ArgumentNullException("entity");
    }
    entities.Remove(entity);
    _applicationDbContext.SaveChanges();
}
public T Get(int Id)
{
    return entities.SingleOrDefault(c => c.Id == Id);
}
public IEnumerable GetAll()
{
    return entities.AsEnumerable();
}
public void Insert(T entity)
{
    if (entity == null)
    {
        throw new ArgumentNullException("entity");
    }
    entities.Add(entity);
    _applicationDbContext.SaveChanges();
}
public void Remove(T entity)
{
    if (entity == null)
    {
        throw new ArgumentNullException("entity");
    }
    entities.Remove(entity);
}
public void SaveChanges()
{
    _applicationDbContext.SaveChanges();
}
public void Update(T entity)
{
    if (entity == null)
    {
        throw new ArgumentNullException("entity");
    }
    entities.Update(entity);
    _applicationDbContext.SaveChanges();
}

}
4. 实现服务层
服务层用来实现核心的业务逻辑。同样先建一个目录CustomerService,方便注入,也是一个接口一个类:

ICustomerService.cs

public interface ICustomerService
{
IEnumerable GetAllCustomers();
Customer GetCustomer(int id);
void InsertCustomer(Customer customer);
void UpdateCustomer(Customer customer);
void DeleteCustomer(int id);
}
CustomerService.cs

public class CustomerService : ICustomerService
{
private IRepository _repository;

public CustomerService(IRepository repository)
{
    _repository = repository;
}

public IEnumerable GetAllCustomers()
{
    return _repository.GetAll();
}
public Customer GetCustomer(int id)
{
    return _repository.Get(id);
}
public void InsertCustomer(Customer customer)
{
    _repository.Insert(customer);
}
public void UpdateCustomer(Customer customer)
{
    _repository.Update(customer);
}
public void DeleteCustomer(int id)
{
    Customer customer = GetCustomer(id);
    _repository.Remove(customer);
    _repository.SaveChanges();
}

}
4. 注入
这儿就是套路了,不解释。

public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddTransient();
}
5. 实现控制器
重要的三层都已经实现。下面做个演示用的控制器:

CustomerController.cs

[ApiController]
[Route("[controller]")]
public class CustomerController : ControllerBase
{
private readonly ICustomerService _customerService;

public CustomerController(ICustomerService customerService)
{
    _customerService = customerService;
}

[HttpGet(nameof(GetCustomer))]
public IActionResult GetCustomer(int id)
{
    var result = _customerService.GetCustomer(id);
    if (result != null)
    {
        return Ok(result);
    }
    return BadRequest("No records found");
}
[HttpGet(nameof(GetAllCustomer))]
public IActionResult GetAllCustomer()
{
    var result = _customerService.GetAllCustomers();
    if (result != null)
    {
        return Ok(result);
    }
    return BadRequest("No records found");
}
[HttpPost(nameof(InsertCustomer))]
public IActionResult InsertCustomer(Customer customer)
{
    _customerService.InsertCustomer(customer);
    return Ok("Data inserted");
}
[HttpPut(nameof(UpdateCustomer))]
public IActionResult UpdateCustomer(Customer customer)
{
    _customerService.UpdateCustomer(customer);
    return Ok("Updation done");
}
[HttpDelete(nameof(DeleteCustomer))]
public IActionResult DeleteCustomer(int Id)
{
    _customerService.DeleteCustomer(Id);
    return Ok("Data Deleted");
}

}
USB Microphone https://www.soft-voice.com/
Wooden Speakers https://www.zeshuiplatform.com/
亚马逊测评 www.yisuping.cn

你可能感兴趣的:(Dotnet洋葱架构实践)