标签: ef-core-2.0

如何从 ASP.NET Identity Core 2.0 中删除与角色相关的表

通过在别处阅读的建议,角色是声明的子集,我正在寻找一种干净的方法来要求 ASP.NET Identity 中的 EF Core 实现不要在 VS 中的 ASP.NET Identity Core 2.0 模板中创建与角色相关的表2017. 只需要索赔。该模板使用

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}
Run Code Online (Sandbox Code Playgroud)

而 IdentityDbContext 创建了这些 Roles 相关的表

https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity.EntityFrameworkCore/IdentityDbContext.cs

如何在不操作迁移文件的情况下摆脱它们?

asp.net-identity asp.net-core-2.0 ef-core-2.0

3
推荐指数
1
解决办法
2272
查看次数

EF Core DbUpdateConcurrencyException无法按预期工作

我有以下代码,我正在尝试使用ef core更新ClientAccount,但是它们并发检查失败:

    public class ClientAccount
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }

        [Required]
        [ConcurrencyCheck]
        public double Balance { get; set; }

        [Required]
        public DateTime DateTimeCreated { get; set; }

        [Required]
        public DateTime DateTimeUpdated { get; set; }       
    }

    public class ClientRepository
    {
        private readonly MyContext context;

        public ClientRepository(MyContext context)
        {
            this.context = context;
        }

        public ClientAccount GetClientAccount()
        {
            return (from client in context.ClientAccount
                    select client).SingleOrDefault();
        }

        public void Update(ClientAccount client)
        {
            context.Update(client);
            context.Entry(client).Property(x => x.DateTimeCreated).IsModified = false; …
Run Code Online (Sandbox Code Playgroud)

.net c# ef-code-first entity-framework-core ef-core-2.0

3
推荐指数
1
解决办法
3674
查看次数

是否可以在EF核心中进行迁移?

我开始使用EF Core 2.0,我有一个针对.NET 4.6.1的控制台应用程序,我有一个非常简单的模型类,并且具有以下上下文:

public class ContextCore : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["efCoreCon"].ConnectionString);
    }
    public DbSet<ModelC> Models { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是连接字符串:

<add name="efCoreCon" connectionString="server=PC-MSHWF\SQLEXPRESS;database=efCoreDB;integrated security=true;" />
Run Code Online (Sandbox Code Playgroud)

我注意到官方文档Enable-Migrations中的ef core中没有命令

所以我跑了,Add-migration firstMigration 但出现了这个错误:

在程序集“ NewConsole”中找不到迁移配置类型。(在Visual Studio中,您可以使用Package Manager控制台中的Enable-Migrations命令来添加迁移配置)。

当我尝试Enable-Migrations时,出现以下错误:

在程序集“ NewConsole”中找不到上下文类型。

c# ef-core-2.0

3
推荐指数
2
解决办法
7468
查看次数

EF Core 2 中的通用实体配置类

我正在尝试为我的实体创建一个通用配置类,但我被卡住了。

我有一个名为 EntityBase 的抽象类:

public abstract class EntityBase
{
    public int Id { get; set; }
    public int TenantId { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime UpdatedOn { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

以及从 EntityBase 继承的许多其他类,其中我必须使用相同的代码在每个类中配置 DateTime 属性。这边走:

void EntityTypeConfiguration<MyEntity>.Configure(EntityTypeBuilder<MyEntity> builder)
    {
        builder.HasIndex(e => e.TenantId);
        builder.Property(e => e.CreatedOn)
              .ValueGeneratedOnAdd()
              .HasDefaultValueSql("GETDATE()");

        // Other specific configurations here
    }
Run Code Online (Sandbox Code Playgroud)

我希望能够调用类似的东西:builder.ConfigureBase() 并避免代码重复。有任何想法吗?

c# entity-framework-core ef-core-2.0

3
推荐指数
1
解决办法
1040
查看次数

属性“ a”不是实体类型“ b”的导航属性。为什么不?

我正在尝试通过以下查询加载产品标识符Label的列表(即产品标识符的名称,例如“ EAN”,“产品编号”等)ProductIdentifiers

ICollection<ProductIdentifierInType> typeIds =
            _context.ProductIdentifiersInTypes
            .Include(t => t.Identifier.Label)
            .OrderBy(o => o.SortOrder).ToList();
Run Code Online (Sandbox Code Playgroud)

VS给了我智慧t.Identifier.Label。解决方案编译良好。这是我得到的运行时错误:

InvalidOperationException:属性“ Label”不是实体类型“ ProductIdentifier”的导航属性。“ include(string)”方法只能与“。”一起使用。导航属性名称的分隔列表。

以下是相关的模型类:

public class ProductIdentifierInType
{
    public int Id { get; set; }
    public int ProductTypeId { get; set; }
    public int SortOrder { get; set; }

    public ProductIdentifier Identifier { get; set; }
    public ProductType Type { get; set; }
}

public class ProductIdentifier
{
    public int Id { get; set; }
    public string Label { get; …
Run Code Online (Sandbox Code Playgroud)

linq entity-framework-core ef-core-2.0

3
推荐指数
1
解决办法
2342
查看次数

在 EF Core 中如何选择特定列并保存

我有以下 SQL 表

 ID INT  
 Status NVARCHAR(50)
 FileContent XML
Run Code Online (Sandbox Code Playgroud)

使用 EF Core 我想选择IDStatus列但不加载 XML 列。(由于 xml 数据可能很大,我不想将其加载到内存中,而且我正在执行的业务逻辑不需要它) ,然后设置Status

public async Task DoSomwthing(int id)
{
    // select only needed columns
    var result = await _dbContext.MyTable
    .Where(x=>x.ID == id)
    .Select(x=> new 
           {
              ID = x.ID,
              Status = x.Status
           })
   .SingleOrDefaultAsync();

   // do something here using result

  // Since i am not loading the complete entity 
  // How do i set the Status here to new value …
Run Code Online (Sandbox Code Playgroud)

entity-framework-core ef-core-2.0

3
推荐指数
1
解决办法
6028
查看次数

在类“Program”上调用方法“BuildWebHost”时出错

当我运行时 dotnet ef migrations add Initial_Identity,出现此错误:

在类“Program”上调用方法“BuildWebHost”时出错。在没有应用程序服务提供商的情况下继续。错误:GenericArguments 1 , 'Microsoft.AspNetCore.Identity.IdentityRole', on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]'s 违反了'TRole' 类型的约束。脚手架操作可能会导致数据丢失。请检查迁移的准确性。

我该如何解决?

这是我的代码:

创业班

public void ConfigureServices(IServiceCollection services)
{
    // some codes
    services.AddIdentity<User, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
}
Run Code Online (Sandbox Code Playgroud)

程序类

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseDefaultServiceProvider(options => options.ValidateScopes = false)
            .Build();
}
Run Code Online (Sandbox Code Playgroud)

TemporaryDbContextFactory 类

public class TemporaryDbContextFactory : 
IDesignTimeDbContextFactory<ApplicationDbContext>
{
    //////// 
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
        IConfigurationRoot …
Run Code Online (Sandbox Code Playgroud)

asp.net entity-framework-core asp.net-core-2.0 ef-core-2.0 entity-framework-migrations

3
推荐指数
1
解决办法
2160
查看次数

EFCore SQLite 连接字符串与asp.net 中的相对路径

我刚刚将 SQLite 添加到我的 asp.net webApi 项目中,并且无法确定如何将 App_Data 文件夹的路径传递给 DbContextOptionsBuilderUseSqlite

我在web.configI have a link to an external a config file with the conenction string ...

<connectionStrings configSource="config\connectionStrings.config"/>
Run Code Online (Sandbox Code Playgroud)

在那里我有...

    <connectionStrings>
      <add name="MyDatastore"
             connectionString="DataSource=./App_Data/test.sqlite" />
    </connectionStrings>
Run Code Online (Sandbox Code Playgroud)

而在我的DbContext.OnConfiguring我有....

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
          if (!optionsBuilder.IsConfigured)
          {
            string path = WebConfigurationManager.ConnectionStrings["MyDatastore"].ConnectionString;
            optionsBuilder.UseSqlite(path);
          }
    }
Run Code Online (Sandbox Code Playgroud)

路径被正确检索(我可以看到我得到了配置的路径 connectionStrings.config

所以./App_Data/test.sqlite传递给optionsBuilder.UseSqlite(path).

但是,我收到以下错误...

SQLite Error 14: 'unable to open database file'. 
Run Code Online (Sandbox Code Playgroud)

如果我刚刚使用connectionString="DataSource=test.sqlite" />它似乎神奇地在 App_Data 文件夹中找到该文件,当我在我的开发机器上运行调试时,但我在另一台机器(发布版本)上遇到了问题。我认为这是路径,尽管我得到的只是“无法打开数据库文件”。

我也试过了。。

 connectionString="DataSource=|DataDirectory|test.sqlite" />
Run Code Online (Sandbox Code Playgroud)

这给了我一个 …

asp.net sqlite asp.net-web-api ef-core-2.0

3
推荐指数
1
解决办法
3443
查看次数

GetEntityTypes:使用EF Core中的.Property <TEntity>的通用版本配置实体属性

在我的EF核心项目中,我有一些从基类DBEntity继承的实体:

public abstract class DBEntity
{
    public int Id { get; set; }

    public DateTime CreatedOn { get; set; }

    public DateTime UpdatedOn { get; set; }

    public EntityStatus EntityStatus { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想为从DBEntity继承的每个实体设置一些具有默认值的特定属性.目前我正在使用此代码:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        var entities = modelBuilder.Model
            .GetEntityTypes()
            .Where(w => w.ClrType.IsSubclassOf(typeof(DBEntity)))
            .Select(p => modelBuilder.Entity(p.ClrType));

        foreach (var entity in entities)
        {

            entity
                .Property("CreatedOn")
                .HasDefaultValueSql("GETDATE()");

            entity
                .Property("UpdatedOn")
                .HasComputedColumnSql("GETDATE()");

            entity
                .Property("EntityStatus")
                .HasDefaultValue(EntityStatus.Created);

        }
    }
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我不想使用字符串常量指定属性名称(对于重构等不好).

有没有办法循环从DBEntity继承的实体并使用属性表达式配置默认值,如下所示:

foreach (var entity in entities)
{
    entity
      .Property(k …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework entity-framework-core ef-core-2.0

3
推荐指数
1
解决办法
684
查看次数

使用EFCore.BulkExtensions时是否需要调用SaveChanges

我开始将EFCore.BulkExtensions用于ef批量操作,它的工作非常好。

(请参阅https://github.com/borisdj/EFCore.BulkExtensions/

我是否还需要调用SaveChanges:

        using (var db = new ReportingContext())
        {
            db.BulkInsertOrUpdate(entities);
            db.SaveChanges();
        }
Run Code Online (Sandbox Code Playgroud)

还是足够好?

        using (var db = new ReportingContext())
        {
            db.BulkInsertOrUpdate(entities);
        }
Run Code Online (Sandbox Code Playgroud)

c# entity-framework-core ef-core-2.0

3
推荐指数
1
解决办法
1201
查看次数