如何在Entity Framework Core 2/C#中实现简单的“复杂类型”?

7
我第一次使用Entity Framework和.Net Core 2.0(我对C#也比较新,但自从1版以来我一直在使用传统的.Net Framework和VB…因此我不是.Net开发的新手),我已经遇到了一个创建数据库的问题。
拿这个简单的场景举例:我想存储一些关于一些电泵的信息。其中两个属性是范围类型的最小/最大值,因此我将其实现为一个简单的类,如下所示:
public class Pump
{
    [Key]
    public int pumpId { get; set; }
    public string pumpName { get; set; }
    public int pumpControlChannel { get; set; }
    public MinMax normalCurrent { get; set; }
    public MinMax normalFlowRate { get; set; }
}

[ComplexType]
public class MinMax
{
    public int min { get; set; }
    public int max { get; set; }
}

从上面的代码你可以看到,我已经尝试使用[ComplexType]装饰器,但没有成功。

无论如何,现在创建一个简单的DBContext类来管理我的Pumps类。我正在使用Sqlite:

public class EFDB : DbContext
{
    public DbSet<Pump> pumps { get; private set; }

    private static DbContextOptions GetOptions(string connectionString)
    {
        var modelBuilder = new DbContextOptionsBuilder();
        return modelBuilder.UseSqlite(connectionString).Options;
    }

    public EFDB(string connectionString) : base(GetOptions(connectionString)) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        try
        {
            // modelBuilder.ComplexType<MinMax>();      // ComplexType not recognised
            base.OnModelCreating(modelBuilder);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debugger.Break();
        }
    }

}

并且最后有一个简单的静态类来调用它(我将其嵌入了一个更大的程序中...如果您想复制此问题,可以将这些代码行粘贴到 program.cs 中):
public static class TryMe
{
    public static void MakeMeFail()
    {
        using (var db = new EFDB("FileName=C:\\temp\\test_effail.db"))
        {
            try
            {
                db.Database.EnsureCreated();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debugger.Break();   // If we hit this line, it fell over
            }
        }
        System.Diagnostics.Debugger.Break();   // If we hit this line, it worked.
    }
}

只需调用TryMe.MakeMeFail(),代码就会在db.Database.EnsureCreated()处失败。

从我所读的所有内容来看,[ComplexType]应该可以实现我的目标...但它确实没有做到。我也找不到modelBuilder.ComplexType<T>在哪里。

可能只是我缺少某个库引用...?上面的代码使用了以下内容:

using System;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

然而,我在任何地方找到的文档/示例都没有显示需要引用哪些库!

提前感谢。

[附言:对于那些已经看到这个问题的人表示歉意,我正在使用EF Core 2.0,而不是EF6]

1个回答

6
典型的情况,总是这样吧?发布5分钟后,你就会发现自己问题的答案... 在这种情况下,答案可以在这里找到: https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities EF Core 将此类实体称为“所有”实体,而不是“复杂类型”。
只需将以下行添加到 `OnModelCreating` 中即可解决问题:
modelBuilder.Entity<Pump>().OwnsOne(p => p.normalCurrent);
modelBuilder.Entity<Pump>().OwnsOne(p => p.normalFlowRate);

数据库现在已经创建成功(我认为是正确的,但我还没有验证)。


只是一个快速的评论需要注意,数据库结构是正确的,创建normalCurrent_min和normalCurrent_max字段,同样适用于normalFlowRate。 - Ade
我尝试将OwnedAttribute添加到类型中,然后我在使用它的每个表上都得到了一个外键,指向第一个表的主键。这似乎不正确。有什么想法如何修复它吗? - Marie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接