如何根据对象的属性生成主键?我需要像hash这样的东西。但是稳定的散列;
public Object1 {
public Object1(string property1, DateTime property2)
{
Property1 = property1;
Property2 = property2;
StableHashID = GetStableHash();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int StableHashID { get; private set; }
public string Property1 { get; private set; }
public DateTime Property2 { get; private set; }
public int GetStableHash()
{
return ...; // ???
}
}
发布于 2020-07-15 08:17:48
我找到了另一个解决方案。
public override int GetStableHash()
{
int result = GetDeterministicHashCode(ErrorCode.ToString());
result = (result * 397) ^ (GetDeterministicHashCode(Property1.ToString()));
result = (result * 397) ^ (GetDeterministicHashCode(Property2.ToString()));
return result;
}
// https://stackoverflow.com/questions/5154970/how-do-i-create-a-hashcode-in-net-c-for-a-string-that-is-safe-to-store-in-a
private int GetDeterministicHashCode(string str)
{
unchecked
{
int hash1 = (5381 << 16) + 5381;
int hash2 = hash1;
for (int i = 0; i < str.Length; i += 2)
{
hash1 = ((hash1 << 5) + hash1) ^ str[i];
if (i == str.Length - 1)
break;
hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
}
return hash1 + (hash2 * 1566083941);
}
}
发布于 2020-07-13 15:09:48
Guid就足够了。如果您只使用Id列作为索引,Guid.NewGuid()
将为您生成一个很好散列。
Guid.NewGuid() makes an actual guid with a unique value, what you probably want.
但是,如果您在解密hash后找到object值,则可以检查;
发布于 2020-07-13 15:20:54
在没有反射的情况下:
public int GetStableHash()
{
var now = DateTime.Now;
var nowInt = (int) now.Kind;
var nowTicks = (ulong) now.Ticks;
return (((ulong) nowInt) << 62) | nowTicks;
}
具有属性:https://stackoverflow.com/a/12393880
编辑:
但我仍然认为GUID已经足够好了--自动生成,增量式的,有EFCore的好处(例如。更新方法)等。
Fluent API:
public override void Configure(EntityTypeBuilder<Entity> entityBuilder)
{
entityBuilder.Property(entity => entity.Id).HasDefaultValueSql("NEWID()");
}
或者使用注释:[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
https://stackoverflow.com/questions/62878557
复制