Getting Started with LINQ in the ScalarDB Cluster .NET Client SDK
The ScalarDB Cluster .NET Client SDK supports querying the cluster with LINQ and some Entity Framework-like functionality.
This SDK doesn't support Entity Framework. Instead, this SDK implements functionality that is similar to Entity Framework.
SQL support must be enabled on the cluster to use LINQ.
Set up classes​
After confirming that SQL support is enabled, create a C# class for each ScalarDB table that you want to use. For example:
using System.ComponentModel.DataAnnotations.Schema;
using ScalarDB.Net.Client.DataAnnotations;
// ...
[Table("ns.statements")]
public class Statement
{
[Column("statement_id", Order = 0), PartitionKey]
public int Id { get; set; }
[Column("order_id", Order = 1), SecondaryIndex]
public string OrderId { get; set; } = String.Empty;
[Column("item_id", Order = 2), SecondaryIndex]
public int ItemId { get; set; }
[Column("count", Order = 3)]
public int Count { get; set; }
}
[Table("order_service.items")]
public class Item
{
[Column("item_id", Order = 0), PartitionKey]
public int Id { get; set; }
[Column("name", Order = 1)]
public string Name { get; set; } = String.Empty;
[Column("price", Order = 2)]
public int Price { get; set; }
}
If a partition key, clustering key, or secondary index consists of more than one column, the Order
property of ColumnAttribute
will decide the order inside the key or index.
Create a context class that has properties for all the tables you want to use. For example:
public class MyDbContext: ScalarDbContext
{
public ScalarDbSet<Statement> Statements { get; set; }
public ScalarDbSet<Item> Items { get; set; }
}
After all the classes are created, you need to add the created context to the Dependency Injection. For example:
using ScalarDB.Net.Client.Extensions;
//...
var builder = WebApplication.CreateBuilder(args);
//...
builder.Services.AddScalarDbContext<MyDbContext>(options =>
{
options.Address = "http://<HOSTNAME_OR_IP_ADDRESS>:<PORT>";
options.HopLimit = 10;
});
The context can be injected into the controller's constructor as follows:
[ApiController]
public class OrderController: ControllerBase
{
private readonly MyDbContext _myDbContext;
public OrderController(MyDbContext myDbContext)
{
_myDbContext = myDbContext;
}
}
Use LINQ to query properties​
After receiving MyDbContext
in your controller, you can query its properties by using LINQ. For example: