2

In Entity Framework we can define a Primary Key on more than one columns.

something like this

public class MyEntity
{
    [Key, Column(Order=0)]
    public int MyFirstKeyProperty { get; set; }

    [Key, Column(Order=1)]
    public int MySecondKeyProperty { get; set; }          
}

Is there any way to achieve such behavior in mongoDb ?

BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47

1 Answers1

-1

you can create CompoundIndex on the database. below link has elaborated on it.

https://docs.mongodb.com/manual/core/index-compound/

in C# you can create this way

           grades.Indexes.CreateMany(Builders<MyCollection>.IndexKeys.Ascending(x => x.Name))

            //if you don't have mycollection, and your collection is of type IMongoCollection<BSonDocument> then you can use this

            grades.Indexes.CreateManyAsync("{ Name: 1 }","{ID:-1}");
KaSh
  • 175
  • 1
  • 11
  • what I have asked for is primary key not indexes ?!! – BRAHIM Kamel May 12 '16 at 12:40
  • 1
    you just have to add attribute {unique:true}. this will enforce unique constraint https://docs.mongodb.com/manual/core/index-unique/ – KaSh May 12 '16 at 13:17
  • 2
    and here why for example you need a primary key not a unique key "In sharded clusters, if you do not use the _id field as the shard key, then your application must ensure the uniqueness of the values in the _id field to prevent errors. This is most-often done by using a standard auto-generated ObjectId". – BRAHIM Kamel May 12 '16 at 13:43
  • Thank you. thats helpful – KaSh May 12 '16 at 14:47
  • may be this will help http://stackoverflow.com/questions/7222062/mongodb-composite-key/7225657#7225657 – KaSh May 16 '16 at 07:23