gpt4 book ai didi

c# - 在 Entity Framework Core 中创建非聚集索引

转载 作者:太空狗 更新时间:2023-10-29 21:21:25 27 4
gpt4 key购买 nike

使用Entity Framework Core,想来个Guid PK,不苦页fragmentation在数据库中。

我看过这个postthis .虽然这在 EF6 中是可能的,但它的完成方式似乎已经改变。

是否可以在 Entity Framework Core 中创建一个非集群主键并有一个额外的索引?

下面的问答。

最佳答案

可以使用 EntityFrameworkCore v1.0.1 或更高版本。

下面的代码得到了想要的结果:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace TestApplication.Models
{

/// <summary>
/// The context class. Make your migrations from this point.
/// </summary>
public partial class TestApplicationContext : DbContext
{
public virtual DbSet<Company> Companies { get; set; }

public TestApplicationContext(DbContextOptions<TestApplicationContext> options) : base(options)
{

}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// standard stuff here...
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>(entity =>
{
entity.Property<Guid>("CompanyId")
.ValueGeneratedOnAdd();

entity.Property<int>("CompanyIndex")
.UseSqlServerIdentityColumn()
.ValueGeneratedOnAdd();

entity.Property(e => e.CompanyName)
.IsRequired()
.HasColumnType("varchar(100)");

// ... Add props here.

entity.HasKey(e => e.CompanyId)
.ForSqlServerIsClustered(false)
.HasName("PK_Company");
entity.HasIndex(e => e.CompanyIndex)
.ForSqlServerIsClustered(true)
.HasName("IX_Company");
});
}
}

/// <summary>
/// The model - put here for brevity.
/// </summary>
public partial class Company
{
public Company()
{
}

public Guid CompanyId { get; set; }
public int CompanyIndex { get; set; }

public string CompanyName { get; set; }
// more props here.
}

}

项目.json

{
"version": "1.0.0-*",

"dependencies": {
"Microsoft.EntityFrameworkCore.Design": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview3-final",
"NETStandard.Library": "1.6.0"
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview3-final",
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netstandard1.6": {
"imports": "dnxcore50"
}
}
}

关于c# - 在 Entity Framework Core 中创建非聚集索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41004292/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com