Home  Dotnet   Simple enti ...

Simple Entity Framework example in dotnet

Entity Framework (EF) is a popular Object-Relational Mapping (ORM) framework for .NET applications, providing a powerful and intuitive way to interact with databases using C#. Here’s a basic example of how Entity Framework can be used in a .NET application:

Setting Up Entity Framework

  1. Install Entity Framework:

    • Entity Framework can be installed via NuGet Package Manager in Visual Studio or using the Package Manager Console:
      Install-Package EntityFramework
      
  2. Create a Data Model:

    • Define your data model classes that correspond to database tables. These classes are annotated with attributes that specify mappings to database columns.
    using System.ComponentModel.DataAnnotations;
    
    public class Product
    {
        [Key]
        public int ProductId { get; set; }
    
        [Required]
        public string Name { get; set; }
    
        public decimal Price { get; set; }
    }
    
  3. DbContext Class:

    • Create a DbContext class that represents a session with the database and provides APIs to query and save data.
    using System.Data.Entity;
    
    public class AppDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
    
        public AppDbContext() : base("name=ConnectionStringName")
        {
        }
    }
    
  4. Connection String:

    • Define a connection string in your application configuration file (app.config or web.config) that points to your database.
    <connectionStrings>
        <add name="ConnectionStringName" connectionString="Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True;" providerName="System.Data.SqlClient" />
    </connectionStrings>
    

Using Entity Framework in Application Code

Now, let's see how you can use Entity Framework in your application to perform CRUD operations (Create, Read, Update, Delete).

  1. Initialization and Usage:

    • Initialize DbContext instance and perform operations:
    using (var dbContext = new AppDbContext())
    {
        // Create
        var newProduct = new Product { Name = "New Product", Price = 99.99 };
        dbContext.Products.Add(newProduct);
        dbContext.SaveChanges();
    
        // Read
        var product = dbContext.Products.Find(1); // Assuming product with ID 1 exists
        Console.WriteLine($"Product ID: {product.ProductId}, Name: {product.Name}, Price: {product.Price}");
    
        // Update
        product.Price = 109.99;
        dbContext.SaveChanges();
    
        // Delete
        dbContext.Products.Remove(product);
        dbContext.SaveChanges();
    }
    
  2. Querying Data:

    • Use LINQ (Language Integrated Query) to query data from the database:
    using (var dbContext = new AppDbContext())
    {
        var expensiveProducts = dbContext.Products.Where(p => p.Price > 100).ToList();
        foreach (var product in expensiveProducts)
        {
            Console.WriteLine($"Product ID: {product.ProductId}, Name: {product.Name}, Price: {product.Price}");
        }
    }
    
Published on: Jul 01, 2024, 09:04 AM  
 

Comments

Add your comment