下面的代码是基于abp生成的项目,项目名:Store
1.在Domain结尾的项目中通过EF工具生成数据实体:
Scaffold-DbContext 'Data Source=服务器IP;Initial Catalog=数据库;User Id=sa;Password=密码;Encrypt=False;' Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables "Cart"
生成后:public partial class Cart,改成public class Cart : Entity<int>
如果第一次使用要在项目添加下面两个包
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
2.实体添加到DbContext中
EF Core需要你将实体和 DbContext
建立关联.最简单的做法是在Acme.Store.EntityFrameworkCore
项目的StoreDbContext
类中添加DbSet
属性.如下所示:
public class StoreDbContext :AbpDbContext<StoreDbContext>,IIdentityDbContext,ITenantManagementDbContext
{/* Add DbSet properties for your Aggregate Roots / Entities here. *///省略了原来的代码,下面是添加的public DbSet<Cart> Cart { get; set; }
}protected override void OnModelCreating(ModelBuilder builder){//省略了原来的代码,下面是添加的builder.Entity<Cart>(b =>{b.ToTable("Cart");});
}
3.Acme.Store.Application.Contracts项目添加:CartDto.cs,ICartAppService.cs
CartDto.cs内容和上面EF工具生成实体是一样的,区别在于要继承EntityDto<int>: public class Cart :EntityDto<int>,Cart这个表我用的是int自增主键,这个需要注意一下,EntityDto<int>这里面类型是可以根据主键类型去调整的,ICartAppService.cs内容如下
public interface ICartAppService :ICrudAppService< //Defines CRUD methodsCartDto, //Used to show int, //Primary key of the entityPagedAndSortedResultRequestDto>{}
4。Acme.Store.Application项目添加:CartAppService.cs
public class CartAppService :
CrudAppService<Cart, CartDto, int, PagedAndSortedResultRequestDto >,
ICartAppService {public CartAppService(IRepository<Cart, int> repository): base(repository){}}}
运行出现在swagger中说明成功了,