EF自动增量问题 [英] EF AutoIncrement Question

查看:94
本文介绍了EF自动增量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





想知道我是否正确地在数据库中正确执行(自动增量)BatchID,如果我手动添加新记录,它将自动增加但是当我通过EF进行操作时,BatchID为零以下是我的模型类(批处理)



Hi,

Wondering if i am doing this correctly (Auto-Increment) of BatchID in the database if i manually add a new record it will auto-increment but when i do it via EF the BatchID is zero below is my model class (Batch)

/// <summary>
    /// Represents a Batch.
    /// </summary>
    [Table(Name = "Batch")]
    public class Batch
    {
        /// <summary>
        /// Gets or sets BatchID.
        /// </summary>
        [Key]
        [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
        public int BatchID { get; set; }

        /// <summary>
        /// Gets or sets Name.
        /// </summary>
        [Column]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the SubBatches
        /// </summary>
        public virtual ICollection<SubBatch> SubBatches { get; set; }
    }





我在哪里使用



Where i use

[Key]
        [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]

这是正确的方法吗?

推荐答案

你甚至不需要放在那里的所有属性。



EF遵循一种约定,即如果类中有一个名为Id的属性或者与附加了Id的类名匹配,则该属性自动成为主[Key]。 br />


除非你要在数据库中制作一些非标准密钥,否则你甚至不需要所有其他东西。自动递增int是默认值。如果你做了不同的事情,那么你可以开始在代码中抛出属性,或者跳过属性并通过Fluent配置来完成。



在你的例子中,所有你需要是这样的:

You really don't even need all of the attributes you put in there.

EF follows a convention that if there is a property in the class that is either called "Id" or that matches the class name with "Id" appended to it, that property is automatically the primary [Key].

You don't even need all the other stuff unless you're going to make some non-standard key in the database. An auto-incrementing int is the default. If you make something different, then you can start throwing attributes at the code, or skip the attributes and do it through the Fluent configuration.

In your example, all you need is this:
public class Batch
{
    public Batch()
    {
        this.SubBatches = new HashSet<SubBatch>();
    }

    public int BatchID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<SubBatch> SubBatches { get; set; }
}



哦,这也有助于初始化集合......


Oh, and it also helps to initialize the collection...


这篇关于EF自动增量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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