我第一次使用Entity Framework和.Net Core 2.0(我对C#也比较新,但自从1版以来我一直在使用传统的.Net Framework和VB…因此我不是.Net开发的新手),我已经遇到了一个创建数据库的问题。
拿这个简单的场景举例:我想存储一些关于一些电泵的信息。其中两个属性是范围类型的最小/最大值,因此我将其实现为一个简单的类,如下所示:
并且最后有一个简单的静态类来调用它(我将其嵌入了一个更大的程序中...如果您想复制此问题,可以将这些代码行粘贴到 program.cs 中):
拿这个简单的场景举例:我想存储一些关于一些电泵的信息。其中两个属性是范围类型的最小/最大值,因此我将其实现为一个简单的类,如下所示:
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]