zer*_*ing 42 c# entity-framework
我创建了一个基于.NET 4.6.2版本的库.
在库中,我添加了EntityFramework版本6.1.3包.
我创建了一个模型如下
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Components.Models
{
public class Session
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }
[Key]
[Required]
public string Identity { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
[Required]
public DateTime UpdatedAt { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
和dbcontext
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Components.Models;
namespace Components.DataContexts
{
public class SessionContext : DbContext
{
public SessionContext() : base(ConfigurationManager.ConnectionStrings["sessiondb"].ConnectionString)
{
}
public DbSet<Session> Sessions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试启用迁移并通过
PM> Enable-Migrations
Run Code Online (Sandbox Code Playgroud)
声明,得到错误信息:
Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=14.1.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable."At D:\C#\IndustryCloud\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:720 char:5
+ $domain.SetData('startUpProject', $startUpProject)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SerializationException
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetProjectTypes(Project project, Int32 shellVersion)
at System.Data.Entity.Migrations.Extensions.ProjectExtensions.IsWebProject(Project project)
at System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade(String configurationTypeName, Boolean useContextWorkingDirectory)
at System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable(String contextTypeName)
at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
更新 结构,如何构建projet
在sessiontest.cs中,我为db编写了测试.
[Test]
public void InsertARow_DbInitial_ExpectDbValue()
{
var sn = new Session()
{
Identity = Random.Generate(15),
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now
};
db.Sessions.Add(sn);
db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
在我编写单元测试的ComponentsTest项目中,app.config看起来如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Session;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" name="sessiondb" />
</connectionStrings>
</configuration>
Run Code Online (Sandbox Code Playgroud)
在库(Component)本身app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Session;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" name="sessiondb" />
</connectionStrings>
</configuration>
Run Code Online (Sandbox Code Playgroud)
Mih*_*man 15
2018更新 - 如果接受的答案没有帮助,请在EF6存储库中查看此github问题.显然,代码迁移命令不适用于新的项目格式.要使迁移命令起作用,您需要创建一个Class Library (.NET Framework)
项目(旧标准),将所有文件移动到那里,添加所有必需的依赖项并运行命令.
编辑:我刚刚Class Library (.NET Standard)
使用EntityFramework 6.2.0在VisualStudio 2017 15.6.6上创建了一个项目.如上所述创建"旧标准"项目可以解决这个问题.
M.H*_*san 14
要明确定义启动项目,可以使用以下命令:
Enable-Migrations -EnableAutomaticMigrations -ProjectName Components -StartupProjectName Components
Run Code Online (Sandbox Code Playgroud)
参数是:
-项目名
指定将脚手架迁移配置类添加到的项目(configuration.cs).如果省略,则使用在包管理器控制台中选择的默认项目.
-StartUpProjectName
指定用于命名连接字符串的配置文件.如果省略,则使用指定项目的配置文件.
要获取该命令的更多详细信息,请运行:
get-help enable-migrations -Full
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26698 次 |
最近记录: |