接上篇 bh002- Blazor hybrid / Maui 保存设置快速教程
源码
10. 添加引用
Index.razor.cs
添加引用
using FreeSql.DataAnnotations;
#if WINDOWS
using Windows.Storage;
#endif
11. 简单使用freesql ORM 初始化数据,添加数据
public partial class Index
{
[DisplayName("用户名")]
[Required(ErrorMessage = "请输入用户名")]
public string NewUsername { get; set; }
List<Users> UserList { get; set; }
string Dbpath { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
StateHasChanged();
}
//添加这句
await OrmTestAsync();
}
}
async Task OrmTestAsync()
{
#if WINDOWS
string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "hybrid.db");
#elif ANDROID || IOS || MACCATALYST
string dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "hybrid.db");
#else
string dbpath = "hybrid.db";
#endif
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, $"Data Source={dbpath};")
//调试sql语句输出
.UseMonitorCommand(cmd => System.Console.WriteLine(cmd.CommandText + Environment.NewLine))
//自动同步实体结构到数据库,FreeSql不会扫描程序集,只有CRUD时才会生成表。
.UseAutoSyncStructure(true)
.UseNoneCommandParameter(true)
.Build();
if (Fsql.Select<Users>().Count() < 1)
{
var itemList = Users.GenerateDatas();
Fsql.Insert<Users>().AppendData(itemList).ExecuteAffrows();
}
UserList= await Fsql.Select<Users>().ToListAsync();
Dbpath = dbpath;
StateHasChanged();
}
async Task Add()
{
Fsql.Insert(new Users() { Username = NewUsername , FullName = "试用用户"}).ExecuteAffrows();
UserList = await Fsql.Select<Users>().ToListAsync();
StateHasChanged();
}
}
12. 用户表实体类
源码工程为了简单起见,都暂时放在同一个文件里面.
/// <summary>
/// 用户表
/// </summary>
public class Users
{
[Column(IsIdentity = true, IsPrimary = true)]
[DisplayName("序号")]
public Guid UserID { get; set; }
//[Column(IsPrimary = true)]
[DisplayName("用户名")]
[Required]
public string Username { get; set; }
[DisplayName("真实姓名")]
[Required]
public string FullName { get; set; }
[DisplayName("启用")]
public bool? Enable { get; set; } = false;
public static List<Users> GenerateDatas()
{
var ItemList = new List<Users>()
{
new Users {
Username = "root" ,
FullName="超级用户",
Enable =false
},
new Users {
Username = "admin" ,
FullName="管理员",
Enable =true
},
new Users {
Username = "guest" ,
FullName="游客",
Enable =false
},
new Users {
Username = "user" ,
FullName="正式用户",
Enable =true
},
};
return ItemList;
}
}
13. 列表数据
Index.razor
<hr />
添加用户:
<InputText @bind-Value="NewUsername" />
<button @onclick="Add">添加</button>
@if (UserList != null)
{
@foreach (var item in UserList)
{
<p><b>@item.FullName</b> <h5>@item.Username</h5></p>
}
}
Dbpath: @Dbpath
14. 运行效果
15. 相关资料
如何远程调试 MAUI blazor / Blazor Hybrid
https://www.cnblogs.com/densen2014/p/16988516.html