使用代码优先的实体框架没有自动增量 [英] Using Entity Framework with code-first no autoincrement

查看:32
本文介绍了使用代码优先的实体框架没有自动增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Movie
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    public virtual IList<Genre> Genre { get; set; }
    public virtual IList<Cast> cast { get; set; }

    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }
}

public class Genre
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public String Name { get; set; }
}

这是我的两个模型.除了在主键上没有实现自动增量外,它们工作得很好.

These are 2 of my models. They work perfectly well, except auto increment isn't implemented on the primary key.

我收到 id 为空的错误,并且无法插入数据库,这在我看来是合乎逻辑的.任何想法为什么没有任何自动增量,其次我如何添加它们?我在 .NET Framework 4.6 中使用代码优先迁移,它是一个 Winforms 应用程序.

I'm getting error of the id being null and not be able to insert into the database which seems logic to me. Any ideas why there aren't any auto increments and secondly how can I add them? I'm using code-first migration in .NET Framework 4.6, it's a Winforms application.

推荐答案

您必须在 ID 列上放置以下两个属性

You will have to put below two attributes on ID column

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

根据此博客:

如果您忘记提及 [Key] ,假设您已将其设为非空,并在 C# 代码中明确说 > Id,则 EF 将尝试传递 NULL,因为它是一个身份,将抛出异常无法插入值NULL 到列………….,所以可以修改DatabaseGeneratedOption.Identity 到 DatabaseGeneratedOption.None –这可能无法满足自动递增的需求.所以,只要保留 [Key]并让 DB 生成器为您填充它.这是当它的方法来到并发.

If you forget to mention [Key] , assuming you have made it not null, and explicitly say > Id in C# code, EF will try to pass NULL since its an identity and will throw an exception "Cannot insert the value NULL into column……….", so can just modify DatabaseGeneratedOption.Identity to DatabaseGeneratedOption.None – which might not fulfill the auto-increment need. So, just keep [Key] and let DB generator to fill it for you. This is the approach when it comes to concurrency.

我希望这能解答您的疑问.

I hope this answers your query.

这篇关于使用代码优先的实体框架没有自动增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆