gpt4 book ai didi

c# - 将长数据属性映射到数据库中的 int

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

在我见过的所有示例中,都使用 int32 作为 ID。这在生产环境中并不总是实用。我们的一些数据库具有 int64 范围内的身份 ID,因此我们的做法是始终使用 long 作为我们的 ID 属性。但是,对于 int 列类型,SQL Server 具有更高的最大值。

我正在使用 Entity Framework 版本 6 进行我们的第一个概念验证。使用 long ID,它无法将对象映射到数据库。

我的所有映射都使用 Fluent API。现在,ID 看起来像这样:

Property(s => s.ID).HasColumnName("spcID");

如果我在上面的末尾添加一个 .HasColumnType("int"),它会给我以下错误:

Schema specified is not valid. Errors: (7,12) : error 2019: Member Mapping specified is not valid. The type 'Edm.Int64[Nullable=False,DefaultValue=]' of member 'ID' in type 'EFConnection.Space' is not compatible with 'SqlServer.int[Nullable=False,DefaultValue=,StoreGeneratedPattern=Identity]' of member 'spcID' in type 'CodeFirstDatabaseSchema.Space'.

如何将这些数据类型映射到 .NET 中的长变量?

编辑

现在,我设置了一个简单的集成测试以确保我可以连接:

[TestMethod]
public void TestMethod1() {
using (var context = new Context()) {
Assert.IsTrue(context.Spaces.Any());
Assert.IsTrue(context.Spaces.First().IsActive);
}
}

没有 .HasColumnType("int"),第一个断言通过,但第二个断言出现 InvalidOperationException:

The 'ID' property on 'Space' could not be set to a 'System.Int32' value. You must set this property to a non-null value of type 'System.Int64'.

最佳答案

C# 和 SQL 数据类型兼容:

如果你的表有一列 bigint 使用 public long Id { get;放; } 如果你的列是 int 使用 public int Id { get;放; }

SQL

bigint -9,223,372,036,854,775,8089,223,372,036,854,775,807int -2,147,483,6482,147,483,647

C#

long -9,223,372,036,854,775,8089,223,372,036,854,775,807int -2,147,483,6482,147,483,647

引用资料:

关于c# - 将长数据属性映射到数据库中的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20803661/

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