NotMapped and AsNoTracking equivalent in FluentMigrator - entity-framework-6

What's the equivalent of NotMapped attribute and AsNoTracking method in Fluent Migrator .Net ORM. I'm migrating one of my project which used EF6 as ORM to Fluent Migrator. I google a lot regarding this but couldn't find any helpful information.

FluentMigrator is an open source project to manage the schema of your data bases, claims to be a .Net implementation similar to Ruby on Rails Migrations, you should post issues and feedback in the issues or discussion forum for that project on github as their community is still active in 2020.
Because Fluent Migrator is not an ORM itself, it only manages the data schema, the question is therefor not properly formed.
EF has it's own schema migration management, Code First Migrations that interprets [NotMapped] to omit the field from the database schema, and to ignore it when mapping results of queries into the data object model.
Project transitions from EF are commonly to NHibernate or Dapper, for this response I will assume NHibernate, because if you were still using EF the problem does not exist but hopefully the thought process will help you find the answer if you are using a different ORM.
RE: NotMapped
As elaborated above, the NotMapped attribute in EF is interpreted by both the data schema migrations AND the ORM. In the configuration for Fluent Migrator you manually specify the fields to manipulate in the data schema, so simply omit the field from Create/Alter table statements altogether.
If you are changing a field to be no longer stored in the database, then you can add a Delete.Column command:
Delete.Column("ColumnName".FromTable("TableName").InSchema("dbo");
UPDATE: Linq2Db solution:
Use NotColumn attribute
In ORMs like NHibernate the same is true, simply do not map the property in the mapping configuration.
This post goes through different solutions when you are using an auto-mapping extension for NHibernate.
RE: AsNoTracking
If you are still using EF6 as the ORM, then this doesn't change, Fluent Migrator is
about schema maintenance and manipulation, not data querying.
AsNoTracking() in an EF query disables change tracking and caching and as a by-product allows a query to return multiple records with duplicate key values in a single response, it is unclear from OP what context AsNoTracking() is being used, but important to identify why is 'might' be used,
UPDATE: linq2Db
As far as I'm aware, Linq2Db does not track changes, its primary function is to translate Linq queries into SQL and execute that SQL, that said AsNoTracking has caching implications so the closest I can find in linq2db is to use NoLinqCache to create a scope where the executions will not be cached:
using (var db = new MyDataConnection())
using (NoLinqCache.Scope())
{
var query = db.Users.Where(x => Sql.Ext.In(x.Id, ids));
}
For readers using NHibernate, you can consult the read-only entities documentation.
You can set al queries in a session as readonly using
session.DefaultReadonly = true
Alternatively you can set a single query to be readonly:
query.SetReadonly(true);

Related

Entity Framework Core Database Table Valued Functions Mapping

I use EFCore 2.1 Database First approach. I'm pretty familiar with SQL syntax and prefer build queries myself rather then leave this work on EF. I use Table Valued and Scalar Functions for querying the database.
I found this for Scalar
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0#database-scalar-function-mapping
But unfortunately nothing about Table Functions.
Is there any way to force Visual Studio grab all Table Functions and Scalar Functions and Stored Procedures from SQL Server, when I run Scaffolding?
I was using LINQ to SQL dbml designer before. Everything was extremely simple with dbml. You drag from Server Explorer drop to dbml and boom, I can use SQL Function or SP like regular C# method.
Any chance to reproduce this in EFCore?
There's no reverse engineer (aka DbContext scaffolding) support for it, but you can use FromSql() to query using table-valued functions. See these docs.
var searchTerm = "EF Core";
var blogResults = db.Blogs.FromSql(
"SELECT * FROM dbo.SearchBlogs({0})",
searchTerm);
Source : https://www.allhandsontech.com/data-professional/entityframework/entity-framework-core-advanced-mapping/
Use HasDbFunction to do a mapping, refer Microsoft doc
It requires return types to be declared as Keyless entity using HasNoKeyMicrosoft doc
Configure EF Context to expose Db function
modelBuilder.HasDbFunction(typeof(SalesContext)
.GetMethod(nameof(NameAndTotalSpentByCustomer)))
.HasName("CustomerNameAndTotalSpent");
modelBuilder.Entity<CustWithTotalClass>().HasNoKey();
Invoke Db function in calling code
_context.NameAndTotalSpentByCustomer().Where(c=>c.TotalSpent>100).ToList();
Generated SQL
SELECT [c].[Name], [c].[TotalSpent]
FROM [dbo].[CustomerNameAndTotalSpent]() AS [c]
WHERE [c].[TotalSpent] > 100

Is it possible NOT to use data annotations attributes ServiceStack OrmLite?

I'm trying to explore the functionality of ServiceStack.OrmLite and can't understand if it possible to use bootstrap class for configuration (foreign keys, data types, column indexes, aliases etc.)? I don't wanna use data annotation attributes on my entity classes. Even usage of some sort of config's would be better than attributes. That is because i wanna have the chance to replace the ORM in future. Maybe exists third-party lib for fluent configuration?
There is no fluent mapping for ServiceStack.OrmLite. I share your reluctance to refer even the DataAnnotations assembly from my Model definitions. I like my POCO's clean as in entirely clean: separate in their own assembly, not referencing any 3rd party assemblies. It's not as much aesthetics as it's a ways of twisting my arm to avoid temptations to do short-hand stuff that breaks good design. I'm like - if it's not a clean ORM, it's just a tightly coupled DAL, and then it's all for nothing anyway.
Anyway - you can definately annotate your POCO classes in a bootstrapping/impl. kind of place - it's really quite obvious: use reflection and add the attribute at runtime, e.g.
typeof (User).GetProperty("Id")
.AddAttributes(new AutoIncrementAttribute());
Same principle of any attribute of OrmLite (and any attribute, really).
I found the hint in the Unit-tests for OrmLite, there's actually a Can_add_AutoIncrement_Id_at_runtime() unit test. Even though this is essentially unit-testing .NET core and not really OrmLite. Thanks, thourough tester-guy, anyway.
ServiceStack OrmLite creates schemas based on code-first POCOs. Adding attributes are a convenience to alter the sql generated table schema if you wanted OrmLite to create the tables for you. If you don't want to use attributes then manually create the SQL Schema in your database out-of-band, or after the tables are created remove the attributes.
Or use another ORM, OrmLite will never support mappings stored in runtime configuration files - which is against it's code-first philosophy.

Self Tracking entities and the mysterious ChangeTracker_ChangeTrackingEnabled datatable column

I'm using Self Tracking Entities that implements IObjectWithChangeTracker with the last Entity Framework RC available as a Nuget. The target database is PostgreSQL. I'm also using Code First fluent API to construct the model and LINQ to Entity for querying the database.
To my surpise, a simple SELECT query on the entity generates a SQL query with a mysterious column ChangeTracker_ChangeTrackingEnabled that does not exist in the datatable ! I do not understand this behavior as it seems to me that the EntityTypeConfiguration derived class maps the entity properties to the datatable columns in its constructor.
Is there a way to disable this behavior or at least tell which column should be mapped by the change tracker ?
For that purpose, Context.Configuration.AutoDetectChangesEnabled = false or calling IsConcurrencyToken() mapping in the EntityTypeConfiguration derived object does not help.
Any help appreciated.
TIA.
You must inform EF about every public property you want to avoid in mapping by either marking property with NotMapped attribute or by using Ignore in fluent API.
Btw. as I know STEs are not designed to be used with code first or DbContext API.

EF 4.1 code first with Existing Database.Mapping Fks,table etc.Clarification needed

I am learning code first and I have project to be used with an existing database.
I am a bit confused of what I meant to be doing.I will explain:
Do I need to create an entityconfiguration for each table in my existing database?
Within this EntityConfiguration for each table do I need to create foreign key relationships?
Do I need to do a ToTable for each table in my existing database?
Is there any free tool "codeplex" that pointing to an existing db will generate this codeFirst stuff?
I have seem few blogs about "EF Code first with existing db" but I am not sure or was not clear to me If Need to create this stuff or I will be getting strange errors like "MyColumn_MyColum" basically as if codeFirst is trying to build some FKs or something.
can somebody clarify?
thanks a lot. I know there are few questions but if you can answer 01 or 2 that would be fine.
thanks again
If you want the code to be generated for you use database-first approach with DbContext API. Simply create EDMX file from your database and let DbContext Generator template generate all entities and context for you.
DbContext Fluent API is mainly targeted to the code-first development approach where EF will created database for you from the code you provided. It can be used with existing database but it requires much more skills and understanding of mapping wich EF can provide to you.
Generally:
You don't need to provide EntityConfiguration for each table if you follow some naming conventions (entity name is singular form of table name, all properties have the same name, primary key in table and entity is named as Id or EntityNameId, etc.).
You don't need to define relationships manually if you follow conventions with exposing navigation properties and possibly also foreign key properties. The issue can be naming of many-to-many keys and junction tables.
ToTable is needed only if your entity does not follow naming convention or if you map some advance inheritance or splitting.
EF uses a lot of default conventions which drive how the names should be defined. Conventions can be removed.
You will not do anything wrong if you define EntityConfiguration for each table - it will at least allow you learning what is needed and your mapping will be explicit / self documented.

Passing a constant value to a stored procedure mapping in Entity Framework

I'm working on creating an Entity Framework model for our database tables, and for the most part, things are going pretty well. However, I'm running into a bit of an issue mapping the stored procedures. See, the homebuilt ORM that our company has been using tends to use one sproc for inserting and updating, and differentiats the operations by passing a bit valued parameter called #IsInsert (I know, don't get me started). Entity Framework seems to expect separate sprocs for inserting and updating, so I figure that all I have to do is tell EF "pass true for this parameter when you're using it as an insert, false if it's an update". However, at least according to the designer UI, it doesn't seem to give me the option for any mapping other than fields on the entity object. Is there a way to pass a constant value (boolean true or false) to a sproc mapping in EF4?
Your best bet may be to use context.executestorequery(query) and keep it how it was before.

Resources