本文介绍了如何使用String属性作为Entity Framework中的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在EF中是新的,并尝试通过ETF6.0中的代码第一个方法来做我的第一步,现在我有一个问题。



我有一个属性

  [Key] 
public string FooId {get;组;

这是我模型的主要关键。



但是,如果我运行

命令在包管理器控制台中更新未完成的迁移到数据库我收到以下错误:

如果我将模型中的PK更改为

  [Key] 
public int FooId {get;组;

一切正常。



但是我需要PK是字符串,因为它在我的情况下是绝对的感觉。我知道有缺点,但对我来说是有必要的。



我在这里看到一个较旧的帖子。



但是似乎没有解决我的问题,或者我只是不明白。



这是真的,我不能使用一个字符串作为一个SQL数据库?



还是有办法呢?

解决方案

这是创建没有启用Identity Autoincrement的PK的正确方式:

  [Key] 
[DatabaseGenerated(DatabaseGeneratedOption .None)]
public string FooId {get;组; }


I'm new in EF and try to do my first steps by code first approach in ETF6.0 and now i have a problem.

I have a property

[Key]
public string FooId { get; set; }

which is my primary key for the model.

But if I run the

command in package manager console to update pending migrations to the database i get the following error:

If I change the PK in my model to

[Key]
public int FooId { get; set; }

everything works fine.

But I would need the PK to be of type string because it makes absolutely sens in my case. I know there are disadvantages but for me it is necessary.

I saw an older post here How to make string as primary key in entity framework!.

But it seems not to solve my problem or I just don't understand it.

Is it really that I can't use a string as PK on a SQL database?

Or is there a way to do that?

解决方案

This is the proper way of creating a PK without Identity Autoincrement enabled:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string FooId { get; set; }

这篇关于如何使用String属性作为Entity Framework中的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 10:40