Asp.net core 学习笔记 ef core Surrogate Key, Natural Key, Alternate Keys

Surrogate Key vs Natural Key, 争论多年 

https://www.mssqltips.com/sqlservertip/5431/surrogate-key-vs-natural-key-differences-and-when-to-use-in-sql-server/

2 个都有好处坏处. 

ef core 对 Natural Key 支持比较弱. 

使用 Alternate Keys 来实现

https://docs.microsoft.com/en-us/ef/core/modeling/alternate-keys

它最糟糕的地方是,目前不支持修改 

https://stackoverflow.com/questions/36200436/cannot-update-alternate-key-entity-framework-core-1-0

https://github.com/aspnet/EntityFrameworkCore/issues/4073

 

对我来说大部分情况下 Surrogate Key 是好用的

但它凡事都要 join 表比较麻烦, filter 也好,查询值也好,都一定要 join.

所以我认为 Natural Key 只在一种情况下特别好

join 的 table 只是一个 primary column

比如有个 category 和 product 

category 只有一个 name, 如果做一个 category 表那每次 product 就得 join category 为了拿唯一的 category name。

而如果 product 直接记入 category name 就方便多了. 

 

短期内 ef 应该是不会支持 update 这个功能的,saveChanges 就报错说不能 edit 了,

目前的 workaround 是去 override migration 生成出来的 file 添加 onUpdate cascade,

table.ForeignKey(
    name: "FK_Products_Categories_categoryName",
    column: x => x.categoryName,
    principalTable: "Categories",
    principalColumn: "name",
    onDelete: ReferentialAction.Restrict,
    onUpdate: ReferentialAction.Restrict);

然后更新的时候直接调用语句.  

var commandText = "update Categories set name = @categoryName where Id = @Id";
var categoryName = new SqlParameter("@categoryName", "man");
var Id = new SqlParameter("@Id", 1);
var ok = Db.Database.ExecuteSqlCommand(commandText, new[] { categoryName, Id });

 

转载于:https://www.cnblogs.com/keatkeat/p/11407886.html

你可能感兴趣的:(Asp.net core 学习笔记 ef core Surrogate Key, Natural Key, Alternate Keys)