使用代码优先的实体框架没有自动增量

编程入门 行业动态 更新时间:2024-10-28 12:17:38
本文介绍了使用代码优先的实体框架没有自动增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..
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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-25 10:51:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1115354.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增量   实体   框架   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!