当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Default Id generating 00000 in MongoDb

问题描述:

I have DB Structure as follow .

public class University

{

[BsonId]

public ObjectId Id { get; set; }

public string Name { get; set; }

public string Code { get; set; }

public IList<College> Colleges { get; set; }

}

public class College

{

[BsonId]

public ObjectId Id { get; set; }

public string Name { get; set; }

public string Code { get; set; }

}

As you can see, An university can have multiple colleges .

I'm adding data is as follow

IList<College> lstColleges=new List<College>();

College clg1=new College(){

Name="Clg1",

Code="CLG1001"

};

College clg2=new College(){

Name="Clg2",

Code="CLG1002"

};

lstColleges.Add(clg1);

lstColleges.Add(clg2);

University unv=new University(){

Name="UNIV",

Code="UN101",

Colleges=lstColleges

};

var collections = mongoDatabase.GetCollection<University>("University");

collections.Insert(unv);

var id = student.unv;

It is correctly Generating Id for University, but for every college, It's generating 000000.

I want to generate a different default Id for each colleges.

网友答案:

Only top level _id are automatically assigned.
Those in an embedded document will need to be manually generated.

You could do this in the ctor:

public class College
{
    public  College 
    {
        Id = ObjectId.GenerateNewId();        
    }

    [BsonId]
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: