Strongly Typed Id #1263
Closed
sonerturkkan
started this conversation in
General
Replies: 1 comment 1 reply
-
.csproj <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FreeSql" Version="3.2.805" />
<PackageReference Include="FreeSql.Provider.Sqlite" Version="3.2.805" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="StronglyTypedId" Version="0.2.1" />
</ItemGroup>
</Project> Program.cs using FreeSql;
using FreeSql.DataAnnotations;
using FreeSql.Internal.Model;
using Newtonsoft.Json;
FreeSql.Internal.Utils.TypeHandlers.TryAdd(typeof(FooId), new FooIdTypeHandler());
var freeSql = new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=:memory:")
.UseMonitorCommand(cmd => Console.WriteLine(cmd.CommandText))
.UseNoneCommandParameter(true)
.UseAutoSyncStructure(true)
.Build();
// insert.
freeSql.Insert(new Foo { Id = FooId.New(), Name = "TEST" }).ExecuteAffrows();
// query all.
var data = freeSql.Select<Foo>().ToList();
// query by id.
freeSql.Select<Foo>().Where(t => t.Id == data[0].Id).ToList();
// serialize to json.
Console.WriteLine(JsonConvert.SerializeObject(data));
public class FooIdTypeHandler : TypeHandler<FooId>
{
public override FooId Deserialize(object value)
{
if (value is string str) return new FooId(new Guid(str));
if (value is Guid uuid) return new FooId(uuid);
throw new Exception();
}
public override object Serialize(FooId value)
{
return value.Value;
}
}
[StronglyTypedId]
public partial struct FooId
{
}
public class Foo
{
// map type is required.
[Column(MapType = typeof(Guid), IsPrimary = true)]
public FooId Id { get; set; }
public string Name { get; set; }
} output: C:/Code/Gitea/Hd2y.TestStrongTypedIds/Hd2y.TestStrongTypedIds/bin/Debug/net8.0/Hd2y.TestStrongTypedIds.exe
select 1 from main.sqlite_master where type='table' and name='Foo'
CREATE TABLE IF NOT EXISTS "main"."Foo" (
"Id" CHARACTER(36) NOT NULL,
"Name" NVARCHAR(255),
PRIMARY KEY ("Id")
)
;
INSERT INTO "Foo"("Id", "Name") VALUES('b8a7bc27-9938-42ab-b605-5c5100fcf3f8', 'TEST')
SELECT a."Id", a."Name"
FROM "Foo" a
SELECT a."Id", a."Name"
FROM "Foo" a
WHERE (a."Id" = 'b8a7bc27-9938-42ab-b605-5c5100fcf3f8')
[{"Id":"b8a7bc27-9938-42ab-b605-5c5100fcf3f8","Name":"TEST"}] |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Thanks for this great library.
Is there any way to use Strongly Typed Id in FreeSQL? https://andrewlock.net/rebuilding-stongly-typed-id-as-a-source-generator-1-0-0-beta-release/
How can I find out any sample or documentation?
Thanks,
Beta Was this translation helpful? Give feedback.
All reactions