温馨提示×

C# ORM框架的关联查询如何编写

c#
小樊
82
2024-08-22 08:39:32
栏目: 编程语言

在C#中使用ORM框架进行关联查询时,一般需要先定义好实体类之间的关联关系,然后根据ORM框架的语法进行查询操作。以下是一个简单的示例代码,使用Entity Framework Core进行关联查询:

// 定义实体类
public class Author
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Book> Books { get; set; }
}

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}

// 创建DbContext
public class LibraryContext : DbContext
{
    public DbSet<Author> Authors { get; set; }
    public DbSet<Book> Books { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("your_connection_string");
    }
}

// 查询操作
using (var context = new LibraryContext())
{
    var authorsWithBooks = context.Authors
        .Include(a => a.Books)
        .ToList();

    foreach (var author in authorsWithBooks)
    {
        Console.WriteLine($"Author: {author.Name}");
        foreach (var book in author.Books)
        {
            Console.WriteLine($"- Book: {book.Title}");
        }
    }
}

在上面的代码中,首先定义了两个实体类Author和Book,并建立了一对多的关联关系。然后创建了一个DbContext类LibraryContext,用于管理数据库连接和实体对象。最后,在查询操作中使用了Include方法来加载Author实体对象的Books导航属性,实现了关联查询的功能。

0