Us PetaPoco and Entity Framework Core 進行開發的一個樣例專案
PetaPoco and Entity Framework Core
資料增刪改查使用PetaPoco進行操作。可惜的是PetaPoco不支援code first,因此專案中使用Entity Framework Core進行code first的處理工作。 根據命名規範,在EFCore的DBContext中對物體的定義使用的複數形式,但是在定義物體的時候使用的是單數。PetaPoco操作時,資料庫表名也為複數形式,因此需要在定義物體的時候加上TableName Attribute。 nuget取用: MySql.Data Pomelo.EntityFrameworkCore.MySql EFCore DBContext新增:
namespace PetaPocoEfCoreMvc.DBContext
{
public class EfCoreDBContext : DbContext
{
public EfCoreDBContext(DbContextOptions options) : base(options)
{
}
public DbSet Users { get; set; }
public DbSet Orders { get; set; }
public DbSet Customers { get; set; }
}
}
PetaPocoDBContext新增:建構式是程式碼【Resharper】生成,其實用到的是最後一個建構式
namespace PetaPocoEfCoreMvc.DBContext
{
public class PetaPocoMvcDBContext:Database
{
public PetaPocoMvcDBContext(DbConnection connection, IMapper defaultMapper = null)
: base(connection, defaultMapper)
{
}
public PetaPocoMvcDBContext(string connectionString, string providerName, IMapper defaultMapper = null)
: base(connectionString, providerName, defaultMapper)
{
}
public PetaPocoMvcDBContext(string connectionString, DbProviderFactory factory, IMapper defaultMapper = null)
: base(connectionString, factory, defaultMapper)
{
}
public PetaPocoMvcDBContext(string connectionString, IProvider provider, IMapper defaultMapper = null)
: base(connectionString, provider, defaultMapper)
{
}
public PetaPocoMvcDBContext(IDatabaseBuildConfiguration configuration)
: base(configuration)
{
}
}
}
資料庫連線字串
"ConnectionStrings": {
"MySQL": {
"MvcMySQL": "server=127.0.0.1;port=3306;uid=root;pwd=123456;database=PetaPocoEfCoreMvc;",
"provider": "MySql.Data.MySqlClient"
}
}
在Startup的ConfigureServices中新增如下程式碼
services.AddDbContext(
options =>
{
var connectionString = Configuration["ConnectionStrings:MySQL:MvcMySQL"];
options.UseMySql(connectionString,
myopttion => { myopttion.ServerVersion(new Version(10,2), ServerType.MariaDb); });
});
services.AddScoped(
(x) =>
{
var connectionStrnig = Configuration["ConnectionStrings:MySQL:MvcMySQL"];
var configuration = DatabaseConfiguration.Build().UsingConnectionString(connectionStrnig)
.UsingProvider();
return new PetaPocoMvcDBContext(configuration);
});
namespace PetaPocoEfCoreMvc.Models
{
[TableName("Users")]
public class User
{
public ulong Id { get; set; }
public Guid Uid { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
}
Bogus使用
定義介面是為了方便DI使用
namespace PetaPocoEfCoreMvc.BogusResp
{
public interface ISampleCustomerRepository
{
IEnumerable GetCustomers();
IEnumerable GetUsers();
}
public class SampleCustomerRepository : ISampleCustomerRepository
{
public IEnumerable GetCustomers()
{
Randomizer.Seed = new Random(123456);
var ordergenerator = new Faker("zh_CN")
.RuleFor(o => o.Id, f => f.Random.ULong(0, 1000))
.RuleFor(o => o.Date, f => f.Date.Past(3))
.RuleFor(o => o.OrderValue, f => f.Finance.Amount(0, 10000))
.RuleFor(o => o.Shipped, f => f.Random.Bool(0.9f));
var customerGenerator = new Faker()
.RuleFor(c => c.Id, f => f.Random.ULong(0, 1000))
.RuleFor(c => c.Name, f => f.Company.CompanyName())
.RuleFor(c => c.Address, f => f.Address.FullAddress())
.RuleFor(c => c.City, f => f.Address.City())
.RuleFor(c => c.Country, f => f.Address.Country())
.RuleFor(c => c.ZipCode, f => f.Address.ZipCode())
.RuleFor(c => c.Phone, f => f.Phone.PhoneNumber())
.RuleFor(c => c.Email, f => f.Internet.Email())
.RuleFor(c => c.ContactName, (f, c) => f.Name.FullName())
.RuleFor(c => c.Orders, f => ordergenerator.Generate(f.Random.Number(10)).ToList());
return customerGenerator.Generate(100);
}
public IEnumerable GetUsers()
{
Randomizer.Seed = new Random(23456789);
var userGenerator = new Faker().RuleFor(u => u.Id, f => f.Random.ULong())
.RuleFor(u => u.Uid, f => f.Random.Guid()).RuleFor(u => u.UserName, f => f.Name.FullName())
.RuleFor(u => u.Password, f => f.Internet.Password(16));
return userGenerator.Generate(20);
}
}
}
AutoMapper doc
AutoMapper.Extensions.Microsoft.DependencyInjection 在Startup的ConfigureServices中新增如下程式碼services.AddAutoMapper(cfg => { },new List(){ Assembly.GetEntryAssembly() });
定義繼承Profile的類
namespace PetaPocoEfCoreMvc.Profiles
{
public interface IProfile
{
}
public class PetaPocoEfCoreProfile:Profile,IProfile
{
public PetaPocoEfCoreProfile()
{
CreateMap().ReverseMap();
}
}
}
MQTTnet
新增nuget取用 :Install-Package MQTTnet.AspNetCore -Version 3.0.0-rc2 使用方法: 在program中的CreateWebHostBuilder新增程式碼:第五行
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseKestrel(
host =>
{
host.ListenAnyIP(1883,lis=>lis.UseMqtt());
host.ListenAnyIP(5000);
})
.UseStartup();
在Startup中新增程式碼:
//Mqtt
services.AddHostedMqttServerWithServices(
builder =>
{
builder.WithDefaultEndpoint();
builder.WithConnectionValidator(
c =>
{
//從IServiceCollection中構建 ServiceProvider, 用以使用註入訪問資料庫的服務
var serprovider = services.BuildServiceProvider();
var us = serprovider.GetService(typeof(IUserService)) as IUserService;
var x = us.GetAll();
if (c.ClientId.Length < 5)
{
c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
return;
}
if (c.Username != "admin")
{
c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
return;
}
if (c.Password != "admin")
{
c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
return;
}
c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
});
});
//this adds tcp server support based on System.Net.Socket
services.AddMqttTcpServerAdapter();
//this adds tcp server support based on Microsoft.AspNetCore.Connections.Abstractions
services.AddMqttConnectionHandler();
//this adds websocket support
services.AddMqttWebSocketServerAdapter();
為能在ConfigureServices中使用註入功能,特別要註意一下程式碼內容:
//從IServiceCollection中構建 ServiceProvider, 用以使用註入訪問資料庫的服務
var serprovider = services.BuildServiceProvider();
var us = serprovider.GetService(typeof(IUserService)) as IUserService;
var x = us.GetAll();
在Configure方法中新增下麵程式碼: app.UseMqttEndpoint();
朋友會在“發現-看一看”看到你“在看”的內容