首页 / 问答 / C#&.NET Core应用程序中EF Core是否可以通过一个方法返回不同类型的对象?

C#&.NET Core应用程序中EF Core是否可以通过一个方法返回不同类型的对象?

0

此问题来自《c# .net core是否可以通过一个方法返回不同类型的对象?》

在C# .NET Core应用程序中写ef core 的时候,想通过一个方法来返回不同类别的类型,这样子只要一个方法就能输出不同类别的表了。

是否可以这么实现?

回复 [×]
提交评论
请输入评论内容

1 个回答

  • 0

    按照问题的描述,可以创建一个泛型的方法来实现一个方法返回不同类型的对象,这是一种泛型仓储的架构模式。
    这里我用EF Core InMemoryDatabase数据提供程序做了一个简单的示例。

    1.安装NuGet程序包

    在项目中使用NuGet程序包管理工具或命令行安装依赖包:Microsoft.EntityFrameworkCore.InMemory

    2.创建MyDbContext.cs数据库连接上下文

    using ConsoleApp2.Models;
    using Microsoft.EntityFrameworkCore;
    
    namespace ConsoleApp2
    {
        internal class MyDbContext : DbContext
        {
            public MyDbContext()
            {
            }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseInMemoryDatabase("DemoDatabase");
            }
    
            public virtual DbSet<Customer> Customers { get; set; }
            public virtual DbSet<Order> Orders { get; set; }
            public virtual DbSet<Address> Addresses { get; set; }
        }
    }
    

    3.创建实体类

    Address.cs

    namespace ConsoleApp2.Models
    {
        public class Address
        {
            public int Id { get; set; }
            public string Province { get; set; }
            public string City { get; set; }
            public string District { get; set; }
            public string Street1 { get; set; }
            public string Street2 { get; set; }
            public string MobilePhone { get; set; }
        }
    }
    

    Customer.cs

    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApp2.Models
    {
        public class Customer
        {
            public Customer()
            {
                CreatedAt = DateTime.Now;
                Addresses = new HashSet<Address>();
            }
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Username { get; set; }
            public string Gender { get; set; }
            public DateTime CreatedAt { get; set; }
            public ICollection<Address> Addresses { get; set; }
        }
    }
    

    Order.cs

    using System;
    
    namespace ConsoleApp2.Models
    {
        public class Order
        {
            public long Id { get; set; }
            public string OrderNo { get; set; }
            public DateTime PurchasedAt { get; set; }
            public double Amount { get; set; }
            public virtual Customer Customer { get; set; }
        }
    }
    

    4.添加示例数据

    DataGenerator.cs

    using ConsoleApp2.Models;
    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApp2
    {
        public class DataGenerator
        {
            public static void Init()
            {
                using var db = new MyDbContext();
                var addresses = new List<Address>
                {
                    new Address { Province = "重庆", City = "重庆", District="江北区",Id=1,Street1="观音桥",MobilePhone="10000"}
                };
                db.Addresses.AddRange(addresses);
                var customer = new Customer
                {
                    Id = 1,
                    FirstName = "刘",
                    LastName = "先生",
                    Username = "rector",
                    Gender = "男",
                    Addresses = addresses
                };
                db.Customers.Add(customer);
                db.Orders.Add(new Order
                {
                    Id = 10000,
                    OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                    Customer = customer,
                    Amount = 3999.99,
                    PurchasedAt = DateTime.Now
                });
                var i = db.SaveChanges(true);
                Console.WriteLine("数据初始化完成.");
            }
        }
    }
    

    最后,再创建一个DbContext的静态类,并在其中创建泛型静态扩展方法,如下:

    using Microsoft.EntityFrameworkCore;
    
    namespace ConsoleApp2
    {
        public static class DbContextExtension
        {
            /// <summary>
            /// 根据ID获取实体对象
            /// </summary>
            /// <typeparam name="TEntity"></typeparam>
            /// <param name="context"></param>
            /// <param name="id"></param>
            /// <returns></returns>
            public static TEntity GetById<TEntity>(this DbContext context, object id) where TEntity : class
            {
                return context.Set<TEntity>().Find(id);
            }
        }
    }
    

    这里只创建了一个名为GetById<TEntity>()的泛型方法,在调用此方法中,指定的TEntity是什么类型,返回的即为什么类型,测试代码如下:

    using ConsoleApp2.Models;
    using System;
    using System.Text.Encodings.Web;
    using System.Text.Json;
    using System.Text.Unicode;
    
    namespace ConsoleApp2
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                DataGenerator.Init();
                JsonSerializerOptions options = new JsonSerializerOptions
                {
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs)
                };
                using var db = new MyDbContext();
                var address = db.GetById<Address>(1);
                Console.WriteLine(JsonSerializer.Serialize(address, options));
    
                var customer = db.GetById<Customer>(1);
                Console.WriteLine(JsonSerializer.Serialize(customer, options));
    
                var order = db.GetById<Order>(10000L);
                Console.WriteLine(JsonSerializer.Serialize(order, options));
    
                Console.ReadKey();
            }
        }
    }
    

    运行结果如图:

    Rector的个人主页

    Rector

    2021-10-14 回答

    我来回答