C# 为什么当我创建一个新模型并尝试检索它的ID时,它总是返回0?

C# 为什么当我创建一个新模型并尝试检索它的ID时,它总是返回0?,c#,visual-studio,entity-framework,model,C#,Visual Studio,Entity Framework,Model,当我创建新模型并尝试检索其ID时,它总是返回0 为什么呢?在我将它添加到相应的集合和上下文之后,我正在尝试它。据我所知,每次创建一个新模型时,它都会调用DB并分配一个唯一的ID StoreGeneratedPattern值在Model.edmx文件中设置为Identify。它将在context.SaveChanges()之后获取数字。在此之前,数据库中没有新模型对象的记录,插入时将生成的id未知 更新: public class Book { public int Id{get;set;

当我创建新模型并尝试检索其ID时,它总是返回0

为什么呢?在我将它添加到相应的集合和上下文之后,我正在尝试它。据我所知,每次创建一个新模型时,它都会调用DB并分配一个唯一的ID


StoreGeneratedPattern值在Model.edmx文件中设置为Identify

它将在
context.SaveChanges()之后获取数字。在此之前,数据库中没有新模型对象的记录,插入时将生成的id未知

更新

public class Book
{
    public int Id{get;set;}
    public string Title{get;set;}
    ....//some other properites
    public virtual Shelve Shelve{get;set;} //navigation property to Shelve where this book is placed
}
public class Shelve
{
    public int Id{get;set;}
    public string Name{get;set}
    ....//some other properties, as example address in library
    public virtual ICollection<Book> Books{get;set;}
}
例如,您有两张桌子:书和书架。任何一本书都可以放在一个书架上,一个书架可以放很多书。典型的一对多关系。 EF在模型中为您生成两个类: 课堂用书

public class Book
{
    public int Id{get;set;}
    public string Title{get;set;}
    ....//some other properites
    public virtual Shelve Shelve{get;set;} //navigation property to Shelve where this book is placed
}
public class Shelve
{
    public int Id{get;set;}
    public string Name{get;set}
    ....//some other properties, as example address in library
    public virtual ICollection<Book> Books{get;set;}
}
班级书架

public class Book
{
    public int Id{get;set;}
    public string Title{get;set;}
    ....//some other properites
    public virtual Shelve Shelve{get;set;} //navigation property to Shelve where this book is placed
}
public class Shelve
{
    public int Id{get;set;}
    public string Name{get;set}
    ....//some other properties, as example address in library
    public virtual ICollection<Book> Books{get;set;}
}
如果您想创建新的书架并将新书添加到其中,则可以使用类似于下一个示例的内容:

var book = new Book();
//initialize properties of book
var shelve = new Shelve(); 
//initialize properties of Shelve
shelve.Books = new List<Book>();
shelve.Books.Add(book);
context.Add(shelve); //add shelve to context
context.SaveChanges();
var book=newbook();
//初始化书本的属性
var shelve=新的shelve();
//初始化搁置的属性
shelve.Books=新列表();
书架。书籍。添加(书籍);
添加(搁置)//将搁置添加到上下文中
SaveChanges();

我明白了。我以为这就是问题所在!:)好的,但假设我有3张表,在一对多关系中。例如,书籍、学生和记录。在记录中,我存储了一本书和一个学生的ID。我必须为一本书和一名学生创建两个新记录,并获取他们的ID,以便创建一个新记录。当我尝试调用SaveChanges()时,我为一本书创建了一个新记录,而为一个学生创建了一个错误…你在书、学生和记录之间有一个导航属性,在EF中的记录中,你应该有公共虚拟属性:书和学生,所以你创建书,创建学生,然后创建记录并分配记录。Book=Book,记录。学生=学生。是的,我有导航属性。你能给我一个简单的例子或链接到像我这样已经解决的问题吗?我将不胜感激!:)我想我明白了。感谢您花费的时间和解释!:)