Skip to content
This repository has been archived by the owner on May 16, 2020. It is now read-only.

Using Managed Foreign Keys

Andrew Grothe edited this page Apr 15, 2017 · 2 revisions

Managed Foreign Keys

In order to use managed foreign keys, ensure you have two entities which inherit from ArangoBaseEntity. ArangoBaseEntity provides the _id, _key and _rev properties which are necessary for foreign keys to work.

Note, currently, updating a document does not updated the related document, they need to be updated independently.

Assuming we have the following Role collection in our database:

public class Role : ArangoBaseEntity {

    [JsonProperty(PropertyName = "name", NullValueHandling = NullValueHandling.Ignore)]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "permission", NullValueHandling = NullValueHandling.Ignore)]
    public string Permission { get; set; }
}

and this User collection:

[Collection(HasForeignKey = true)]
public class User : ArangoBaseEntity
{
    [JsonProperty(PropertyName = "userName", NullValueHandling = NullValueHandling.Ignore)]
    public string Username { get; set; }

    [JsonProperty(PropertyName = "passwd", NullValueHandling = NullValueHandling.Ignore)]
    public string Password { get; set; }

    [ArangoField(ForeignKeyTo = "Role")]
    [JsonConverter(typeof(ForeignKeyConverter))]
    public List<Role> Roles { get; set; } 
}

Now we can Insert and Get the User Model.

var client = ArangoClient.Client();

Role r = new Role()
{
    Name = "sysadmin",
    Permission = "RW"
};
Role r2 = new Role()
{
    Name = "author",
    Permission = "RW"
};

UpdatedDocument uR1 = await client.DB().InsertAsync(r);
UpdatedDocument uR2 = await client.DB().InsertAsync(r2);

var user = new User()
{
    Username = "andrew",
    Password = "passcode",
    Roles = new List<Role>() { uR1.New, uR2.New}
};

UpdatedDocument u1 = await client.DB().InsertAsync(user);

Now we can retrieve the users with the following:

List<User> users = await client.DB().GetAllAsync<User>();
List<User> users = await client.DB().GetByExampleAsync<User>(new { userName = "andrew"});
User u = client.DB().GetByKeyAsync<User>("23773");

The user is stored in Arango as

[
  {
    "_id": "User/23773",
    "_key": "23773",
    "_rev": "_U06oZZ6---",
    "passwd": "passcode",
    "userName": "andrew",
    "Roles": [
      "23756",
      "23769"
    ]
  }
]

And the Roles as:

[
  {
"_id": "Role/23769",
"_key": "23769",
"_rev": "_U06oZYa---",
"name": "author",
"permission": "RW"
  },
  {
"_id": "Role/23756",
"_key": "23756",
"_rev": "_U06oMu----",
"name": "sysadmin",
"permission": "RW"
  }
]
Clone this wiki locally