小编Nie*_*oes的帖子

我们可以使用枚举作为类型安全实体ID吗?

我们正在使用EF 6.1代码首次设置中的一个相当大的模型,我们正在使用实体ID的int.

不幸的是,这不像我们想要的那样是类型安全的,因为人们可以很容易地混合id,例如比较不同类型的实体(myblog.Id == somePost.Id)或类似的ID.甚至更糟:myBlog.Id ++.

因此,我提出了使用类型ID的想法,因此您无法混淆ID.所以我们需要为我们的博客实体提供BlogId类型.现在,显而易见的选择是使用包装在结构中的int,但不能使用结构作为键.而你无法扩展... ...等等,你可以!使用枚举!

所以我想出了这个:

public enum BlogId : int { } 
public class Blog
{
    public Blog() { Posts = new List<Post>(); }
    public BlogId BlogId { get; set; }
    public string Name { get; set; }
    public virtual List<Post> Posts { get; set; }
}
internal class BlogConfiguration : EntityTypeConfiguration<Blog>
{
    internal BlogConfiguration()
    {
        HasKey(b => b.BlogId);
        Property(b=>b.BlogId)
           .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以现在我们有了类型安全ID - 比较BlogId和PostId是编译时错误.我们不能将3添加到BlogId.空的枚举可能看起来有点奇怪,但这更像是一个实现细节.我们必须在映射中显式设置DatabaseGeneratedOption.Identity选项,但这是一次性的努力.

在我们开始将所有代码转换为此模式之前,是否有任何明显的问题?

编辑:我可能需要澄清为什么我们必须首先使用id而不是完整实体.有时我们需要匹配EF Linq查询中的实体 - 并且比较实体在那里不起作用.例如(基于博客示例并假设更丰富的域模型):在当前用户博客条目上查找评论.请记住,我们希望在数据库中执行此操作(我们有大量数据),并且我们假设没有直接的导航属性.并且当前的用户没有附加.一种天真的方法

from c in ctx.Comments where …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework entity-framework-6

17
推荐指数
1
解决办法
609
查看次数

从命令行运行时,mstest v2忽略ExpectedException

我正在尝试使用新的"mstest v2"框架,但在从命令行运行mstest.exe测试时遇到问题.具体来说,ExpectedExceptionAttribute和DeploymentItemAttribute不起作用.

这是我的样本测试:

[TestMethod]
[ExpectedException(typeof(NotImplementedException))]
public void ExpectedExceptionShouldWork()
{
    throw new NotImplementedException(
       "This exception should not cause the test to fail");
}
Run Code Online (Sandbox Code Playgroud)

我很确定它是由从Microsoft.VisualStudio.TestPlatform.TestFramework程序集而不是从Microsoft.VisualStudio.QualityTools.UnitTestFramework中拾取的属性引起的 - 然后mstest.exe无法识别它们.

我们在构建服务器(Teamcity)中运行mstest.exe,并且测试在那里失败,即使它们在IDE中成功.在本地运行时,Mstest.exe也会失败

"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\MSTest.exe" /testcontainer:bin\Debug\Dummy.Test.dll
Run Code Online (Sandbox Code Playgroud)

当我的项目引用Microsoft.VisualStudio.QualityTools.UnitTestFramework时,它可以在命令行和IDE中工作.

如果我然后添加一个nuget引用到MSTest.TestFramework v 1.1.13,我得到一个编译错误:

Error   CS0433  
The type 'TestClassAttribute' exists in both 
'Microsoft.VisualStudio.QualityTools.UnitTestFramework, 
Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' and 
'Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, 
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Run Code Online (Sandbox Code Playgroud)

当我删除对Microsoft.VisualStudio.QualityTools.UnitTestFramework的引用时,它在IDE中编译并工作 - 但不是从命令行.测试已运行,但由于抛出异常而失败.

我们真的想使用来自mstest v2的新东西,比如[DataTestMethod],但是我们不能在构建服务器上使构建失败.

有没有解决方法?它不只是关于[ExpectedException]?其他属性如[AssemblyInitialize]似乎也被忽略了?

c# mstest

2
推荐指数
1
解决办法
1057
查看次数

标签 统计

c# ×2

entity-framework ×1

entity-framework-6 ×1

mstest ×1