You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Entity Framework Code-First配置多表One-None/One关系及CRUD语句

嘿,既然你已经确认实体模型没问题,那咱们直接上手写对应的CRUD LINQ操作吧!先理清楚咱们的核心关系:Player和DKImages是一对一依赖关系(Player必须关联DKImages才能保存),Products和DKImages也是一对一依赖关系(Products同样必须关联DKImages),而且DKImages作为主体实体,Player和Products的主键同时是DKImages的外键,所以它们的ID必须和关联的DKImages的ImageID保持一致。


创建(Create)

因为Player和Products必须依赖DKImages才能保存,所以创建时要么先单独保存DKImages再关联,要么直接通过导航属性让EF自动处理保存顺序(更推荐后者)。

创建Player并关联DKImages

using (var context = new YourDbContext()) // 替换成你的DbContext类名
{
    // 1. 构建DKImages实例
    var playerImage = new DKImages
    {
        ImageURL = "/assets/images/player-jordan.jpg",
        DateUploaded = DateTime.Now,
        CategoryID = 1 // 假设分类1是玩家图片
    };

    // 2. 构建Player实例并关联图片
    var newPlayer = new Player
    {
        PlayerName = "Michael",
        PlayerLastName = "Jordan",
        PlayerAge = 61,
        Position = Positions.SG,
        Starter = true,
        Status = false,
        PlayerStatsID = 5, // 假设已有对应的PlayerStats记录
        Images = playerImage // 直接关联导航属性,EF会自动处理ID匹配
    };

    // 3. 添加并保存,EF会先保存DKImages再保存Player,自动同步ID
    context.Players.Add(newPlayer);
    context.SaveChanges();
}

创建Products并关联DKImages

using (var context = new YourDbContext())
{
    var productImage = new DKImages
    {
        ImageURL = "/assets/images/product-jersey.jpg",
        DateUploaded = DateTime.Now,
        CategoryID = 2 // 假设分类2是产品图片
    };

    var newProduct = new Products
    {
        ProductName = "Chicago Bulls Jersey",
        DateAdded = DateTime.Now,
        ProductTypeID = 3, // 假设已有对应的ProductType记录
        Images = productImage
    };

    context.Products.Add(newProduct);
    context.SaveChanges();
}

查询(Read)

使用Include方法预加载关联的DKImages,避免延迟加载带来的N+1查询问题。

查询单个Player及其关联图片

using (var context = new YourDbContext())
{
    var playerWithImage = context.Players
        .Include(p => p.Images) // 预加载关联的DKImages
        .FirstOrDefault(p => p.PlayerID == 1);

    if (playerWithImage != null)
    {
        Console.WriteLine($"Player: {playerWithImage.PlayerName} {playerWithImage.PlayerLastName}");
        Console.WriteLine($"Image URL: {playerWithImage.Images.ImageURL}");
    }
}

查询所有Products及其关联图片

using (var context = new YourDbContext())
{
    var productsWithImages = context.Products
        .Include(p => p.Images)
        .ToList();

    foreach (var product in productsWithImages)
    {
        Console.WriteLine($"Product: {product.ProductName}");
        Console.WriteLine($"Image URL: {product.Images.ImageURL}");
    }
}

查询DKImages及其关联的Player/Products

using (var context = new YourDbContext())
{
    // 查询图片关联的Player(如果有的话)
    var imageWithPlayer = context.DKImages
        .Include(i => i.Player)
        .FirstOrDefault(i => i.ImageID == 1);

    if (imageWithPlayer?.Player != null)
    {
        Console.WriteLine($"Image belongs to Player: {imageWithPlayer.Player.PlayerName}");
    }

    // 查询图片关联的Products(如果有的话)
    var imageWithProduct = context.DKImages
        .Include(i => i.Products)
        .FirstOrDefault(i => i.ImageID == 2);

    if (imageWithProduct?.Products != null)
    {
        Console.WriteLine($"Image belongs to Product: {imageWithProduct.Products.ProductName}");
    }
}

更新(Update)

可以同时更新实体本身和关联的DKImages信息,同样需要预加载关联实体。

更新Player及其关联图片

using (var context = new YourDbContext())
{
    var playerToUpdate = context.Players
        .Include(p => p.Images)
        .FirstOrDefault(p => p.PlayerID == 1);

    if (playerToUpdate != null)
    {
        // 更新Player属性
        playerToUpdate.PlayerAge = 62;
        playerToUpdate.Status = true;

        // 更新关联的图片属性
        playerToUpdate.Images.ImageURL = "/assets/images/player-jordan-2024.jpg";
        playerToUpdate.Images.DateUploaded = DateTime.Now;

        context.SaveChanges();
    }
}

更新Products及其关联图片

using (var context = new YourDbContext())
{
    var productToUpdate = context.Products
        .Include(p => p.Images)
        .FirstOrDefault(p => p.ProductID == 2);

    if (productToUpdate != null)
    {
        productToUpdate.ProductName = "Chicago Bulls Retro Jersey";
        productToUpdate.Images.ImageURL = "/assets/images/product-jersey-retro.jpg";

        context.SaveChanges();
    }
}

删除(Delete)

删除时需要注意:默认情况下,删除Player/Products不会自动删除关联的DKImages(因为依赖关系是Player/Products依赖DKImages),你可以根据业务需求选择仅删除依赖实体,或者同时删除关联的DKImages。

仅删除Player,保留DKImages

using (var context = new YourDbContext())
{
    var playerToDelete = context.Players.Find(1);
    if (playerToDelete != null)
    {
        context.Players.Remove(playerToDelete);
        context.SaveChanges();
        // DKImages中对应的记录会被保留,只是Player记录被删除
    }
}

删除Player同时删除关联的DKImages

using (var context = new YourDbContext())
{
    var playerToDelete = context.Players
        .Include(p => p.Images)
        .FirstOrDefault(p => p.PlayerID == 1);

    if (playerToDelete != null)
    {
        // 先删除关联的图片,再删除Player
        context.DKImages.Remove(playerToDelete.Images);
        context.Players.Remove(playerToDelete);
        context.SaveChanges();
    }
}

删除Products同时删除关联的DKImages

using (var context = new YourDbContext())
{
    var productToDelete = context.Products
        .Include(p => p.Images)
        .FirstOrDefault(p => p.ProductID == 2);

    if (productToDelete != null)
    {
        context.DKImages.Remove(productToDelete.Images);
        context.Products.Remove(productToDelete);
        context.SaveChanges();
    }
}

内容的提问来源于stack exchange,提问作者Parsa9oo0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:54:10