<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Entity FrameWork Core]]></title><description><![CDATA[<p dir="auto">This section is to briefly introduce how to configure entity framework core to and <a href="http://ASP.NET" target="_blank" rel="noopener noreferrer nofollow ugc">ASP.NET</a> Core project and do few CRUD operations.</p>
<p dir="auto"><strong>Prerequisite: atleast worked with Entity Framework 6</strong></p>
<p dir="auto">Create a class library project as a Data Access layer project in your solution so that the Web project and the the database can be separated.</p>
<p dir="auto">Install the following nuget packages from the nuget manager to have entity frame work correctly configured.</p>
<ol>
<li>
<p dir="auto">To get the fully supported version of EFCore with sql, install Microsoft.entityframeworkcore.sqlserver from the nuget. This will pull in all the dependencies.<br />
To see the diagram of the  tables, install <a href="https://marketplace.visualstudio.com/items?itemName=ErikEJ.EFCorePowerTools" target="_blank" rel="noopener noreferrer nofollow ugc">https://marketplace.visualstudio.com/items?itemName=ErikEJ.EFCorePowerTools</a> (read documentation for mo info).</p>
</li>
<li>
<p dir="auto">In order to execute migrations, install the following tool and do the migration using the package manager console. EF Core2 doesn’t come with all the EF tools like in EF 6. Not everybody will run migrations. So if u want to run migrations install the following tool.</p>
</li>
</ol>
<p dir="auto">Using nuget package manager, install: Microsoft.entityframeworkcore.tools</p>
<p dir="auto">•	When running migrations, make sure that the package manager console points to the right project, which is the Data Access project</p>
<p dir="auto">•	To get a list of commands of EFcore, type “get-help entityframeworkcore”</p>
<pre><code>Cmdlet                      Description
</code></pre>
<p dir="auto">•	        --------------------------  ---------------------------------------------------<br />
•	        Add-Migration               Adds a new migration.<br />
•	<br />
•	        Drop-Database               Drops the database.<br />
•	<br />
•	        Get-DbContext               Gets information about a DbContext type.<br />
•	<br />
•	        Remove-Migration            Removes the last migration.<br />
•	<br />
•	        Scaffold-DbContext          Scaffolds a DbContext and entity types for a database.<br />
•	<br />
•	        Script-Migration            Generates a SQL script from migrations.</p>
<ol start="3">
<li>Once you run the add-migration command, I will get an error like this:</li>
</ol>
<p dir="auto"><img src="/assets/uploads/files/1548902795929-1-resized.png" alt="0_1548902796747_1.png" class=" img-responsive img-markdown" /></p>
<p dir="auto">•	This is because the Data project and the Domain project are class library projects. The StartUp project must have the references to the Data and the Domain project. There fore, add the reference to the StartUp project and install the following nuget package to the StartUp Project.</p>
<p dir="auto">o	Microsoft.entityframeworkcore.design</p>
<p dir="auto">•	This is because the design project needs and executable project and not a class library project .<br />
•	Set the executable project as the startup project.<br />
•	Now run the add-migration command again and it will succeed Inshah Allah</p>
<p dir="auto"><strong>Model SnapShot file</strong><br />
•	The model snapshot file is very important because this is where entity framework will keep track of the current state of the model. When a new migration is added the ef core will read the snapshot and compare it with the new version of the model and figures out what needs to be changed.</p>
<p dir="auto"><strong>Migrations</strong><br />
•	To create a sql script of the migration, type the command<br />
<img src="/assets/uploads/files/1548902952081-2.png" alt="0_1548902953075_2.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Runnin this command will generate a sql script like the example below</strong></p>
<p dir="auto">IF OBJECT_ID(N'[__EFMigrationsHistory]') IS NULL<br />
BEGIN<br />
CREATE TABLE [__EFMigrationsHistory] (<br />
[MigrationId] nvarchar(150) NOT NULL,<br />
[ProductVersion] nvarchar(32) NOT NULL,<br />
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])<br />
);<br />
END;</p>
<p dir="auto">GO</p>
<p dir="auto">CREATE TABLE [Battles] (<br />
[Id] int NOT NULL IDENTITY,<br />
[Name] nvarchar(max) NULL,<br />
[StartDate] datetime2 NOT NULL,<br />
[EndDate] datetime2 NOT NULL,<br />
CONSTRAINT [PK_Battles] PRIMARY KEY ([Id])<br />
);</p>
<p dir="auto">GO</p>
<p dir="auto">CREATE TABLE [Samurais] (<br />
[Id] int NOT NULL IDENTITY,<br />
[Name] nvarchar(max) NULL,<br />
[BattleId] int NOT NULL,<br />
CONSTRAINT [PK_Samurais] PRIMARY KEY ([Id]),<br />
CONSTRAINT [FK_Samurais_Battles_BattleId] FOREIGN KEY ([BattleId]) REFERENCES [Battles] ([Id]) ON DELETE CASCADE<br />
);</p>
<p dir="auto">GO</p>
<p dir="auto">CREATE TABLE [Quotes] (<br />
[Id] int NOT NULL IDENTITY,<br />
[Text] nvarchar(max) NULL,<br />
[SamuraiId] int NOT NULL,<br />
CONSTRAINT [PK_Quotes] PRIMARY KEY ([Id]),<br />
CONSTRAINT [FK_Quotes_Samurais_SamuraiId] FOREIGN KEY ([SamuraiId]) REFERENCES [Samurais] ([Id]) ON DELETE CASCADE<br />
);</p>
<p dir="auto">GO</p>
<p dir="auto">CREATE INDEX [IX_Quotes_SamuraiId] ON [Quotes] ([SamuraiId]);</p>
<p dir="auto">GO</p>
<p dir="auto">CREATE INDEX [IX_Samurais_BattleId] ON [Samurais] ([BattleId]);</p>
<p dir="auto">GO</p>
<p dir="auto">INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])<br />
VALUES (N'20181113023641_init', N'2.1.4-rtm-31024');</p>
<p dir="auto">GO</p>
<p dir="auto">•	Update the databse using the <strong>update-database</strong> command from the package manager console, this will create a db in your mssql server if the db doesn't exist r update it.</p>
<p dir="auto"><strong>One-to-Many and-Many-to-Many</strong></p>
<p dir="auto"><img src="/assets/uploads/files/1548903116473-3-resized.png" alt="0_1548903117335_3.png" class=" img-responsive img-markdown" /></p>
<p dir="auto">•	One samaurai can fight in many battles and many samurais can fight in one battles. There for many to many relationship.<br />
•	Create a new table (many to many relationship) as SamuriBattle.<br />
•	Create the many to many relationship relationship using the ef core fluent API in the SamuriContext file.<br />
•	Here, we have a composite primary key</p>
<p dir="auto"><img src="/assets/uploads/files/1548903168071-4-resized.png" alt="0_1548903169026_4.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Logging sql script created by Ef core</strong></p>
<p dir="auto">•	install the package Microsoft.Extensions.Logging.Console to SamaruiAppData (the class libabry project for the db access) project</p>
<p dir="auto"><img src="/assets/uploads/files/1548903264895-5.png" alt="0_1548903265948_5.png" class=" img-responsive img-markdown" /></p>
<p dir="auto">This code must be added to the App datacontext class which inherits the DbContext class so we can see the generated sql</p>
<p dir="auto"><strong>Inserting a list of objects to databse using ef core 2</strong></p>
<p dir="auto"><img src="/assets/uploads/files/1548903320069-6.png" alt="0_1548903321128_6.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Inserting different types of objects to the database using AddRange() method in ef core 2</strong></p>
<p dir="auto"><img src="/assets/uploads/files/1548903359512-7-resized.png" alt="0_1548903360361_7.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Usling Like() in ef core 2</strong></p>
<p dir="auto">•	use the like() method instead of contains which will finally convert into a Like() method taking in a wild card.<br />
•	EF is a built in function</p>
<p dir="auto"><img src="/assets/uploads/files/1548903399166-8-resized.png" alt="0_1548903400191_8.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>selecting the last recored using LastOrDefault()</strong></p>
<p dir="auto"><img src="/assets/uploads/files/1548903441335-9-resized.png" alt="0_1548903442378_9.png" class=" img-responsive img-markdown" /></p>
<p dir="auto">•	Here, the ef core will generate a sql ordered by decending and select the top.</p>
<p dir="auto"><img src="/assets/uploads/files/1548903483846-10.png" alt="0_1548903484903_10.png" class=" img-responsive img-markdown" /></p>
<p dir="auto">•	If orderBy() is not included, the sql will return a list to the memory and then will select the last record which is a performance hit.</p>
<p dir="auto"><strong>Using the Find() method</strong></p>
<p dir="auto">•	The Find method will return an object by taking in the primary key of the entity. If the entity is tracked by the context in will be return from the memory without doing a call to the database. Cool ha!</p>
<p dir="auto"><img src="/assets/uploads/files/1548903538565-11.png" alt="0_1548903539575_11.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Disconnected Updates</strong></p>
<p dir="auto">•	 Here, there is no tracking of the entity by the dbcontext<br />
•	We can use the Update method to update the object without tracking what properties have been change.</p>
<p dir="auto"><img src="/assets/uploads/files/1548903582102-12.png" alt="0_1548903583069_12.png" class=" img-responsive img-markdown" /></p>
<p dir="auto">•	Here all though only the EndDate has been changed, the context object is different when updating the object.<br />
•	The Using statement will create a new context object and pass the entity to the Update method.<br />
•	All the properties will be updated, not just only the EndDate</p>
<p dir="auto"><img src="/assets/uploads/files/1548903618081-13-resized.png" alt="0_1548903618952_13.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Simplified methods</strong></p>
<p dir="auto"><img src="/assets/uploads/files/1548903646303-14.png" alt="0_1548903647298_14.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Deleting</strong></p>
<p dir="auto">•	Delete can be done using the Remove() method if u have the entity object to pass into the Remove() function.<br />
•	If u have only the primary key, we can use a raw sql command to execute stored procedure.</p>
<p dir="auto"><img src="/assets/uploads/files/1548903682655-15.png" alt="0_1548903683660_15.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Eager Loading</strong></p>
<p dir="auto"><img src="/assets/uploads/files/1548903738917-16.png" alt="0_1548903739955_16.png" class=" img-responsive img-markdown" /></p>
<p dir="auto">•	The “ThenInclude()” method drills down into the Quotes which is in the “Include()” and retrieves that data as well</p>
<p dir="auto"><img src="/assets/uploads/files/1548903767244-17-resized.png" alt="0_1548903768086_17.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Projection</strong></p>
<p dir="auto"><img src="/assets/uploads/files/1548903804645-18-resized.png" alt="0_1548903805563_18.png" class=" img-responsive img-markdown" /></p>
<p dir="auto">•	The below query brings out only the samarui object without the Quotes. This query will look for any samurai that has the word ”happy ” in any of its quotes.  Quotes is not included in the result set</p>
<p dir="auto"><img src="/assets/uploads/files/1548903829214-19-resized.png" alt="0_1548903830194_19.png" class=" img-responsive img-markdown" /></p>
<p dir="auto"><strong>Entry method</strong></p>
<p dir="auto"><img src="/assets/uploads/files/1548903856469-20.png" alt="0_1548903857435_20.png" class=" img-responsive img-markdown" /></p>
<p dir="auto">•	When updating a related object when there is no tracking, use the method Entry() and set the entity state to modified as in the image above. This will tell the ef core to only update the modified related object. Not all the object.<br />
•	If we use the update method, it will update all the related objects even if there are no changes.</p>
]]></description><link>https://lankadevelopers.lk/topic/125/entity-framework-core</link><generator>RSS for Node</generator><lastBuildDate>Sat, 11 Jul 2026 11:14:06 GMT</lastBuildDate><atom:link href="https://lankadevelopers.lk/topic/125.rss" rel="self" type="application/rss+xml"/><pubDate>Thu, 31 Jan 2019 03:06:30 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Entity FrameWork Core on Thu, 31 Jan 2019 07:25:26 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="https://lankadevelopers.lk/uid/650">@tnlthanzeel</a>  Thanks Bro</p>
]]></description><link>https://lankadevelopers.lk/post/838</link><guid isPermaLink="true">https://lankadevelopers.lk/post/838</guid><dc:creator><![CDATA[Nubelle]]></dc:creator><pubDate>Thu, 31 Jan 2019 07:25:26 GMT</pubDate></item></channel></rss>