How to: Consume Fluent Mapping Model
You need a project that will consume your data project. For the sake of simplicity, add to your solution a new Console Application and name it Client. You might be asking why you created a separated project for your classes. The answer is simply because you want to compile your classes into a separate and distinct assembly from the UI project. In order to consume your fluent model, all you have to do is:
- Integrate the Telerik.DataAccess.Core NuGet package with the Client project,
- Copy the App.config file from the model project and paste it in the Client project, and
- Add a reference to the model project.
An additional step you need to consider is making the client (consuming) project a start up project. Right-click the client (consuming) project in Solution Explorer and select Set as Startup Project.
Migrating Your Database
The following code-snippet calls the UpdateSchema method of the context to migrate the backend database to the latest model state.
using ( FluentModel dbContext = new FluentModel() )
{
dbContext.UpdateSchema();
}
Using dbContext As New FluentModel()
dbContext.UpdateSchema()
End Using
Performing CRUD Operations
You can use the context class for CRUD operations as well.
using ( FluentModel dbContext = new FluentModel() )
{
dbContext.UpdateSchema();
Product p = new Product
{
Id = 1,
Name = "MyProduct"
};
Category c = new Category
{
Id = 1,
Name = "MyCategory"
};
p.Category = c;
dbContext.Add( p );
dbContext.Add( c );
dbContext.SaveChanges();
foreach ( Product item in dbContext.Products )
{
Console.WriteLine( item.Name );
}
}
Using dbContext As New FluentModel()
dbContext.UpdateSchema()
Dim p As Product = New Product With
{.Id = 1,
.Name = "MyProduct"}
Dim c As Category = New Category With
{.Id = 1,
.Name = "MyCategory"}
p.Category = c
dbContext.Add(p)
dbContext.Add(c)
dbContext.SaveChanges()
For Each item As Product In dbContext.Products
Console.WriteLine(item.Name)
Next item
End Using