-
Notifications
You must be signed in to change notification settings - Fork 4
CRUD Reading One Entity
berkeleybross edited this page Mar 19, 2018
·
5 revisions
There are several overloads for reading a single entity
- Find - Find an entity by it's id, or null.
- Get - Find an entity by it's id, or throw an exception.
- GetFirstOrDefault - Find the first matching entity by some conditions, or null.
- GetFirst - Find the first matching entity by some conditions, or throw an exception.
- GetSingleOrDefault - Find the only matching entity by some conditions, or null.
- GetSingle - Find the only matching entity by some conditions, or throw an exception.
// Synchronous
TEntity Find<TEntity>(object id, int? commandTimeout = null);
// Asynchronous
Task<TEntity> FindAsync<TEntity>(object id, int? commandTimeout = null, CancellationToken cancellationToken = default);
Find an entity by it's id, or null if it doesn't exist. The type of the id should match the type of the primary key of the TEntity
- e.g. if the primary key is a int, then the id should also be an int. If the primary key is a composite key, then the id should be an object which has the properties of the composite key.
[Table("Users")]
public class UserEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
...
var entity = database.Find<User>(12);
// or
var entity = await database.FindAsync<User>(12);
MS-SQL 2012 +
SELECT [Id], [Name]
FROM [Users]
WHERE [Id] = 12
PostgreSQL
SELECT id, name
FROM user
WHERE id = 12
// Synchronous
TEntity Get<TEntity>(object id, int? commandTimeout = null)
where TEntity : class;
// Asynchronous
Task<TEntity> GetAsync<TEntity>(object id, int? commandTimeout = null, CancellationToken cancellationToken = default)
where TEntity : class;
Get an entity by it's id, or throws an exception if it doesn't exist.
📝 Find
and Get
are identical, except that Get
throws an exception when the entity does not exist, similar to FirstOrDefault()
vs First()
[Table("Users")]
public class UserEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
...
var entity = database.Get<User>(12);
// or
var entity = await database.GetAsync<User>(12);
MS-SQL 2012 +
SELECT [Id], [Name]
FROM [Users]
WHERE [Id] = 12
PostgreSQL
SELECT id, name
FROM user
WHERE id = 12