-
Notifications
You must be signed in to change notification settings - Fork 4
Database contexts
The database "context" differes depending on which database type is being used.
The DatabaseContext
class will be the link between C# objects that you use in the code to the database tables where the data is being stored. So the structure of the objects defined here needs to align with the database structure.
For each table you will be interacting with you will need to add a DbSet
to the DatabaseContext
class. For example if you have two tables, one for Person and one for address it might look like this.
public DbSet<Person> People { get; set; }
public DbSet<Address> Addresses { get; set; }
The entities Person
and Address
would also need to be defined, again mapping to the table details which they represent. For example, the address entity might look like this.
[Table("stored_addresses")]
public class Address
{
[Column("addid")]
public int Id { get; set; }
[Column("postcode")]
public string Postcode { get; set; }
[Column("personid")]
[ForeignKey(Person)]
public Int PersonId { get; set; }
[ForeignKey("PersonId")]
public Person Person { get; set; }
}
The values in the Column
attributes must be the names of the database columns and the value in the Table
attribute must be the name of the table. You can also define a foreign key reference here using the ForeignKey
attribute, this means entity framework will map the Person
entity straight onto the address entity for you.
For DynamoDb there is no corresponding "Context" class as there is for Postgres. As above, each database entity must use attributes to declare certain information, as shown below:
[DynamoDBTable("stored_addresses", LowerCamelCaseProperties = true)]
public class Address
{
[DynamoDBHashKey]
public int Id { get; set; }
[DynamoDBProperty]
public string Postcode { get; set; }
[DynamoDBProperty]
public Int PersonId { get; set; }
}
The property marked with DynamoDBHashKey
specifies that this property is used as the key (primary key in relations database terms). This property must also be specified on the table itself withi DynamoDb.