{"id":29895,"date":"2017-02-09T10:49:02","date_gmt":"2017-02-09T18:49:02","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=29895"},"modified":"2019-04-04T08:34:29","modified_gmt":"2019-04-04T15:34:29","slug":"building-android-apps-entity-framework","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/building-android-apps-entity-framework\/","title":{"rendered":"Building Android Apps with Entity Framework"},"content":{"rendered":"<p>\t\t\t\tData is a big part of any application development and mobile apps are no exception; the way we handle data as developers is one of the many important decisions we must make for our mobile apps. From key-value stores to SQLite, there are many options available, but one that .NET developers are often especially familiar with is the Entity Framework. <\/p>\n<p>Entity Framework is an object-relational mapper (O\/RM) that enables .NET developers to work with a database using .NET objects and eliminates the need for more of the data-access code that developers usually need to write. Entity Framework is great, but was difficult to use in mobile development projects\u2014until Entity Framework Core came along. Entity Framework Core is a lightweight, extensible, cross-platform version of Entity Framework data access technology. <\/p>\n<h2>What is Entity Framework Core?<\/h2>\n<p>Entity Framework Core (EF Core) introduces many new features and improvements when compared to full-scale Entity Framework, but is a completely brand new codebase that&#8217;s optimized for cross-platform applications. If you have experience with Entity Framework, you&#8217;ll find EF Core very familiar. Even though it doesn&#8217;t have all of the same features, many will show up in future releases (such as lazy loading and connection resiliency). Because EF Core is .NET Standard-compatible, we can now use it with Xamarin.Android.<\/p>\n<p>Due to it&#8217;s ease-of-use, EF Core has been one of my favorite projects for quite some time. The challenge has always been, &#8220;how can I use the Entity Framework in my Xamarin apps?&#8221; In this blog post, I&#8217;ll show you how to do just that by building an Android app with a backing Entity Framework Core database.<\/p>\n<h2>Getting Started<\/h2>\n<h3>Creating the .NET Standard Library<\/h3>\n<p>To get started, let&#8217;s <a href=\"https:\/\/blog.xamarin.com\/net-standard-library-support-for-xamarin\/\">create a .NET Standard library<\/a>. .NET Standard is a formal specification of the .NET APIs that are intended to be available on all .NET runtimes, similar to Portable Class Libraries. This library is where we&#8217;ll place all of our shared application code, including our Entity Framework Core logic.<\/p>\n<p>Create a new solution and add a Portable Class Library (PCL) to that solution.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/1.png\" alt=\"1\" width=\"689\" height=\"388.5\" class=\"aligncenter size-full wp-image-29926\" \/><\/p>\n<p>Since this isn&#8217;t a .NET Standard (<code>netstandard<\/code>) library, we can convert it by right-clicking the project and navigating to the Properties:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/12.28.2016-12.19.png\" alt=\"12.28.2016-12.19\" width=\"502.5\" height=\"396\" class=\"aligncenter size-full wp-image-29905\" \/><\/p>\n<p>According to NuGet, the requirements of the <code>Microsoft.EntityFrameworkCore<\/code> and <code>Microsoft.EntityFrameworkCore.Sqlite<\/code> packages specify that the library needs to target <code>netstandard 1.3<\/code>. We can change the target in the same place:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/12.28.2016-12.21.png\" alt=\"12.28.2016-12.21\" width=\"666\" height=\"343\" class=\"aligncenter size-full wp-image-29906\" \/><\/p>\n<p>We then need to add the Entity Framework packages to our project. Right-click the <strong>References<\/strong> folder, select <strong>Manage NuGet Packages&#8230;<\/strong>, and install the <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.EntityFrameworkCore\" target=\"_blank\"><code>Microsoft.EntityFrameworkCore<\/code><\/a> and <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.EntityFrameworkCore.Sqlite\/\" target=\"_blank\"><code>Microsoft.EntityFrameworkCore.Sqlite<\/code><\/a> packages.<\/p>\n<p>Great! Now we&#8217;re ready to start diving into some Entity Framework code.<\/p>\n<h3>Defining the DbContext<\/h3>\n<p>If you&#8217;ve used Entity Framework before, you&#8217;ll be very familiar with how we define a <code>DbContext<\/code> and our underlying <code>Models<\/code> that define our database schema.<\/p>\n<p>Let&#8217;s start with a simple data model that we&#8217;ll call <code>Cat<\/code>.<\/p>\n<pre class=\"theme:vs2012 lang:cs decode:true\">\nusing System.ComponentModel.DataAnnotations;\nusing System.Threading.Tasks;\n...\n    public class Cat\n    {\n        [Key]\n        public int CatId { get; set; }\n        public string Name { get; set; }\n        public int MeowsPerSecond { get; set; }\n    }\n<\/pre>\n<p>Next, let&#8217;s ensure that our <code>Cat<\/code> class is part of our <code>DbContext<\/code> by defining a new context called <code>CatContext<\/code>.<\/p>\n<pre class=\"theme:vs2012 lang:cs decode:true\">\nusing Microsoft.EntityFrameworkCore;\n...\n    public class CatContext : DbContext\n    {\n        public DbSet Cats { get; set; }\n\n        private string DatabasePath { get; set; }\n\n        public CatContext()\n        {\n\n        }\n\n        public CatContext(string databasePath)\n        {\n            DatabasePath = databasePath;\n        }\n\n        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)\n        {\n            optionsBuilder.UseSqlite($\"Filename={DatabasePath}\");\n        }\n    }\n<\/pre>\n<h2>Using Entity Framework Core with Xamarin.Android<\/h2>\n<h3>Getting Started<\/h3>\n<p>Now that we have our database configured in our .NET Standard library with EF Core, let&#8217;s create an Android project to connect to this database from. Right-click the solution, click <strong>Add Project<\/strong>, and select <strong>Single-View App (Android)<\/strong>.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/12.28.2016-12.22.png\" alt=\"12.28.2016-12.22\" width=\"470.5\" height=\"326.5\" class=\"aligncenter size-full wp-image-29907\" \/><\/p>\n<p>Just like before, we need to add the \n<a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.EntityFrameworkCore\" target=\"_blank\"><code>Microsoft.EntityFrameworkCore<\/code><\/a> and <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.EntityFrameworkCore.Sqlite\/\" target=\"_blank\"><code>Microsoft.EntityFrameworkCore.Sqlite<\/code><\/a> NuGet packages to our Android project.<\/p>\n<h3>Implementing the Context<\/h3>\n<p>First, we need to make sure our Xamarin.Android project is referencing our .NET Standard library. In the Android project, right-click the References folder, select <strong>Add Reference&#8230;<\/strong>, and then select the library we created at the beginning of this blog post. Click <strong>OK<\/strong> to save this reference.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/12.28.2016-13.01.png\" alt=\"12.28.2016-13.01\" width=\"524\" height=\"362\" class=\"aligncenter size-full wp-image-29908\" \/><\/p>\n<p>Now that we have that, let&#8217;s implement our <code>MainActivity.cs<\/code> with some Entity Framework code!<\/p>\n<pre class=\"theme:vs2012 lang:cs decode:true\">\nusing System.IO;\nusing Microsoft.EntityFrameworkCore;\nusing System.Diagnostics;\nusing EntityFrameworkWithXamarin;\nusing EntityFrameworkWithXamarin.Core;\nusing System.Collections.Generic;\n...\n  [Activity(Label = \"EntityFrameworkWithXamarin.Droid\", MainLauncher = true, Icon = \"@drawable\/icon\")]\n    public class MainActivity : Activity\n      {\n        int count = 1;\n\n        protected async override void OnCreate(Bundle bundle)\n        {\n          base.OnCreate(bundle);\n\n          \/\/ Set our view from the \"main\" layout resource\n          SetContentView(Resource.Layout.Main);\n          \/\/ Get our button from the layout resource,\n          \/\/ and attach an event to it\n          Button button = FindViewById<Button>(Resource.Id.MyButton);\n\n          button.Click += delegate { button.Text = string.Format(\"{0} clicks!\", count++); };\n\n          TextView textView = FindViewById(Resource.Id.TextView1);\n\n          var dbFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);\n          var fileName = \"Cats.db\";\n          var dbFullPath = Path.Combine(dbFolder, fileName);\n          try\n          {\n            using (var db = new CatContext(dbFullPath))\n            {\n              await db.Database.MigrateAsync(); \/\/We need to ensure the latest Migration was added. This is different than EnsureDatabaseCreated.\n\n              Cat catGary = new Cat() { CatId = 1, Name = \"Gary\", MeowsPerSecond = 5 };\n              Cat catJack = new Cat() { CatId = 2, Name = \"Jack\", MeowsPerSecond = 11 };\n              Cat catLuna = new Cat() { CatId = 3, Name = \"Luna\", MeowsPerSecond = 3 };\n\n              List catsInTheHat = new List() { catGary, catJack, catLuna };\n\n              if(await db.Cats.CountAsync() &lt; 3)\n              {\n                await db.Cats.AddRangeAsync(catsInTheHat);\n                await db.SaveChangesAsync();\n              }\n\n              var catsInTheBag = await db.Cats.ToListAsync();\n\n              foreach(var cat in catsInTheBag)\n              {\n                textView.Text += $&quot;{cat.CatId} - {cat.Name} - {cat.MeowsPerSecond}&quot; + System.Environment.NewLine;\n              }\n            }\n\n          }\n          catch (Exception ex)\n          {\n            System.Diagnostics.Debug.WriteLine(ex.ToString());\n          }\n        }\n     }\n<\/pre>\n<p>And now add the <code>TextView1<\/code> to our <code>Resources &gt; Layout &gt; Main.axml<\/code> to which we&#8217;re referring in our <code>MainActivity<\/code>.<\/p>\n<pre class=\"theme:vs2012 lang:xml decode:true\">\n  &lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n  &lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\n      android:orientation=\"vertical\"\n      android:layout_width=\"match_parent\"\n      android:layout_height=\"match_parent\"\n      &gt;\n  &lt;Button  \n      android:id=\"@+id\/MyButton\"\n      android:layout_width=\"match_parent\" \n      android:layout_height=\"wrap_content\" \n      android:text=\"@string\/Hello\"\n      \/&gt;\n  &lt;TextView\n      android:id=\"@+id\/TextView1\"\n      android:layout_width=\"match_parent\"\n      android:layout_height=\"wrap_content\"\n      \/&gt;\n  &lt;\/LinearLayout&gt;\n<\/pre>\n<p>Next, let&#8217;s set our Android project as the startup project and run it in the emulator! Whoops, looks like we&#8217;ll get an error:<\/p>\n<pre class=\"theme:vs2012 lang:html decode:true\">\nMicrosoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such table: Cats'.\n<\/pre>\n<h3>Generating an EF Core Migration<\/h3>\n<p>We&#8217;re missing a core Entity Framework feature called <code>Migrations<\/code> that creates our database schema. At the moment, there isn&#8217;t a great way to generate Entity Framework Migrations from within a Xamarin.Android project or the .NET Standard library. Let&#8217;s use a quick workaround by creating a new <code>netcore<\/code> Console Application so we can generate <code>Migrations<\/code>.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/12.28.2016-13.56.png\" alt=\"12.28.2016-13.56\" width=\"470.5\" height=\"326.5\" class=\"aligncenter size-full wp-image-29909\" \/><\/p>\n<p>To generate our <code>Migrations<\/code>, add the <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.EntityFrameworkCore.Tools.DotNet\" target=\"_blank\"><code>Microsoft.EntityFrameworkCore.Tools.DotNet<\/code><\/a>, <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.EntityFrameworkCore.Design\" target=\"_blank\"><code>Microsoft.EntityFrameworkCore.Design<\/code><\/a>, and <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.EntityFrameworkCore\" target=\"_blank\"><code>Microsoft.EntityFrameworkCore<\/code><\/a> NuGet packages to this project so we can use the command line to generate our <code>Migrations<\/code>.<\/p>\n<p><em>Note: Microsoft.EntityFrameworkCore.Tools.DotNet is currently prerelease and as such you&#8217;ll need to enable the <code>Include prerelease<\/code> checkbox in the NuGet Package Manager if you haven&#8217;t already.<\/em><\/p>\n<p>We now need to move our <code>Cat<\/code> and <code>CatContext<\/code> over to ensure there&#8217;s a <code>DbContext<\/code> it can generate <code>Migrations<\/code> for. Now we can generate a schema for our context. Let&#8217;s use the new <code>dotnet<\/code> tooling to do this. Open up a new console in our current Console App directory:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/12.28.2016-14.03.png\" alt=\"12.28.2016-14.03\" width=\"489.5\" height=\"259.5\" class=\"aligncenter size-full wp-image-29911\" \/><\/p>\n<p>Generate a Migration by running:<\/p>\n<p><code>dotnet ef migrations add Initial<\/code><\/p>\n<p>which will generate the following:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/12.28.2016-14.11.png\" alt=\"12.28.2016-14.11\" width=\"489.5\" height=\"259.5\" class=\"aligncenter size-full wp-image-29912\" \/><\/p>\n<p>Now we need to take the initial migrations generated in the Migrations folder of our project and move them over to our .NET Standard library.<\/p>\n<p><em>Note: You can simply change the namespaces of these two generated files to the name of your <code>netstandard<\/code> namespace.<\/em><\/p>\n<h3>Putting it All Together<\/h3>\n<p>Run the Xamarin.Android project again and we&#8217;re now using Entity Framework Core successfully from our Android application to store data!<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/12.28.2016-14.16.png\" alt=\"12.28.2016-14.16\" width=\"309\" height=\"568\" class=\"aligncenter size-full wp-image-29913\" \/><\/p>\n<p>We can take a closer look at the <code>SQLite<\/code> file that gets generated by using an emulator and opening up the Android Device Monitor. Looking in the <code>data\/data\/files<\/code> folder, we&#8217;ll see our <code>Cats.db<\/code> that we created.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/12.28.2016-14.19.png\" alt=\"12.28.2016-14.19\" width=\"445\" height=\"234\" class=\"aligncenter size-full wp-image-29914\" \/><\/p>\n<p>We can open this file in any SQLite explorer by selecting the file, clicking <em>Pull a file from the device<\/em>, and saving it locally, seen below using <a href=\"http:\/\/sqlitebrowser.org\/\">DB Browser for SQLite<\/a>.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/sqlbrowser.png\" alt=\"sqlbrowser\" width=\"600\" height=\"401\" class=\"aligncenter size-full wp-image-29915\" \/><\/p>\n<h2>Wrapping Up<\/h2>\n<p>In this blog post, we used Entity Framework Core to generate a database we can use from within a Xamarin.Android application. For more information, check out the Entity Framework Core documentation. You can grab my full source code for building Android applications with Entity Framework by going to my <a href=\"https:\/\/github.com\/JonDouglas\/EntityFrameworkWithXamarin\">GitHub<\/a>.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Data is a big part of any application development and mobile apps are no exception; the way we handle data as developers is one of the many important decisions we must make for our mobile apps. From key-value stores to SQLite, there are many options available, but one that .NET developers are often especially familiar [&hellip;]<\/p>\n","protected":false},"author":551,"featured_media":29913,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[5,4],"class_list":["post-29895","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-android","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>Data is a big part of any application development and mobile apps are no exception; the way we handle data as developers is one of the many important decisions we must make for our mobile apps. From key-value stores to SQLite, there are many options available, but one that .NET developers are often especially familiar [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/29895","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/551"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=29895"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/29895\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=29895"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=29895"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=29895"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}