Base entity in many to many relationships - asp.net

I'm trying to implement BaseEntity class.
There i have fields:
Id, CreatedDateTime, UpdatedDateTime, CreatedBy, UpdatedBy.
In my repository class i point this:
public interface IRepositoryBase<TEntity> where TEntity : BaseEntity
Is it will be correct to inherit BaseEntity also in every many-to-many entity?
Like this:
public class OrderDish
{
public int OrderId { get; set; }
public Order Order { get; set; }
public int DishId { get; set; }
public Dish Dish { get; set; }
}

If your BaseEntity looks like this:
public interface BaseEntity
{
DateTime? CreatedDate { get; set; }
DateTime? UpdatedDate { get; set; }
string CreatedBy { get; set; }
string UpdatedBy { get; set; }
}
Create an Entity class from BaseEntity like:
public class Entity : BaseEntity
{
protected Entity(){}
public virtual string CreatedBy { get; set; }
public virtual DateTime? CreatedDate { get; set; }
public virtual string UpdatedBy { get; set; }
public virtual DateTime? UpdatedDate { get; set; }
}
Inherit the other entitites from Entity like:
public class OrderDish : Entity
{
public int OrderId { get; set; }
public Order Order { get; set; }
public int DishId { get; set; }
public Dish Dish { get; set; }
}
You will be able to access the properties this way

Related

how to create relationship in code first in asp.net core

Failed executing DbCommand (13ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE [AspNetUsers] ADD CONSTRAINT [FK_AspNetUsers_Citys_City_ID] FOREIGN KEY ([City_ID]) REFERENCES [Citys] ([ID]) ON DELETE CASCADE;
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint FK_AspNetUsers_Citys_City_ID. The conflict occurred in database UserDBtest3", table "dbo.Citys", column 'ID'.
class City
public class City
{
[Key]
public int ID { get; set; }
[MaxLength(150)]
public string Name { get; set; }
public int State_ID { get; set; }
[ForeignKey("State_ID")]
public virtual State State { get; set; }
public ICollection<ApplicationUser> ApplicationUsers { get; set; }
public City()
{
ApplicationUsers = new List<ApplicationUser>();
}
}
class user
public class ApplicationUser : IdentityUser<int>
{
[Column(TypeName ="nvarchar(150)")]
public string FullName { get; set; }
public bool Active { get; set; }
public int UserRoleID { get; set; }
[ForeignKey("UserRoleID")]
public virtual UserRoleTest UserRoleTest { get; set; }
public int Person_ID { get; set; }
[ForeignKey("Person_ID")]
public virtual Person Person { get; set; }
public int City_ID { get; set; }
[ForeignKey("City_ID")]
public virtual City City { get; set; }
public int State_ID { get; set; }
[ForeignKey("State_ID")]
public virtual State State { get; set; }
}
}
Data context
public class AuthenticationContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
public AuthenticationContext(DbContextOptions<AuthenticationContext> option):base(option)
{
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<UserRoleTest> UserRoleTests { get; set; }
public DbSet<Person> Prsons { get; set; }
public DbSet<Report> Reports { get; set; }
public DbSet<Message> Messages { get; set; }
public DbSet<City> Citys { get; set; }
public DbSet<State> States { get; set; }
}
According to Entity Framework documentation.
If you want relationships to be discovered by convention, can follow the pattern: <principal entity name><primary key property name>
public class City
{
[Key]
public int CityId { get; set; }
//...omitted for brevity
}
public class ApplicationUser : IdentityUser<int>
{
// omitted for brevity
public City City { get; set; }
public int CityId { get; set; }
}
Or if you prefer dont use the convention, you can use the [ForeignKey] annotation:
public class City
{
[Key]
public int Id { get; set; }
//...omitted for brevity
}
public class ApplicationUser : IdentityUser<int>
{
// omitted for brevity
[ForeignKey("IdCity")]
public City City { get; set; }
public int IdCity { get; set; }
}
Or if you prefer not to have a foreign key property (not recommended).
If no foreign key property is found, a shadow foreign key property will be introduced.
public class City
{
[Key]
public int CityId { get; set; }
//...omitted for brevity
}
public class ApplicationUser : IdentityUser<int>
{
// omitted for brevity
public City City { get; set; }
}

Need to create an API on the basis of ForeignKey in dotnet core

Here is my Schema and with two Foreign Key in an intermediate table. I am beginner in Core dotnet so unable to crate API to show the department in the school.
public class DepartmentSchool
{
public int Id { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department{ get; set; }
public int SchoolsId { get; set; }
[ForeignKey("SchoolsId")]
public virtual Schools Schools { get; set; }
Here I want to get all department related to school id, how can i get all the department though the School id in dotnetcore API.
Here is the school class entity schema.
public partial class Schools
{
public int ID { get; set; }
public string UicCode { get; set; }
public int SchoolSystemsId { get; set; }
public string BannerUrl { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public int UserID { get; set; }
public int? Status { get; set; }
public DateTime? CreatedAt { get; set; }
public int? CreatedBy { get; set; }
public DateTime UpdatedAt { get; set; }
public int? ModifiedBy { get; set; }
[ForeignKey("SchoolSystemsId")]
public PrivateSchoolSystem PrivateSchoolSystems { get; set; }
And more here is the department schema.
public partial class Department
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public int CreatedBy { get; set; }
public int UpdatedBy { get; set; }
public int SchoolSystemsID { get; set; }
[ForeignKey("SchoolSystemsID")]
public virtual PrivateSchoolSystem PrivateSchoolSystems { get; set; }
And I am trying to get a department list in the query in the following controller.
[Route("api/[controller]")]
[ApiController]
public class DepartmentSchoolController : ControllerBase
{
private readonly learning_gpsContext _learning_GpsContext;
public DepartmentSchoolController(learning_gpsContext learning_GpsContext)
{
_learning_GpsContext = learning_GpsContext;
}
[HttpGet("school/{schoolId}/departments")]
public IActionResult GetDepartmentsFromSchool(int schoolId)
{
var school = _learning_GpsContext.Schools.Where(e=>e.Id == schoolId).FirstOrDefault();
if (school == null)
return NotFound();
var departments = _learning_GpsContext.DepartmentSchool
.Where(e=>e.SchoolsId == schoolId).Select(e=>e.Department);
return Ok(departments);
}
For further learning check this tutorial. You should also understand what REST is and for basic questions always take a look at the official documenation.

Create SQLite table from an inherited class

I want to create a SQLite table based on the GroupEntity class which inherits from the Entity class.
When I try to create a table directly from GroupEntity class without inheritance - table creates successfully.
I am using SQLite-net, Version=1.4.118.0 in Xamarin.Forms PCL project.
public class Entity
{
public virtual int Id { get; set; }
public DateTime CreatedOn { get; set; }
public int CreatedById { get; set; }
public DateTime ModifiedOn { get; set; }
public int ModifiedById { get; set; }
}
public class GroupEntity : Entity
{
[SQLite.PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
public int PhotoFileId { get; set; }
public int UnreadMessageCount { get; set; }
public Guid LastMessageId { get; set; }
}

Entity Framework Table Per Type inheritance with discriminator column

I am using EF5 TPT and thus don't expect a discriminator column. Why is it being created?
The ( simplified) table classes are;
[Table("SalesDocumentHeaders")]
public abstract class SalesDocumentHeader : LoggedEntity
{
[ForeignKey("CreatedByUserId")]
public virtual User CreatedBy { get; set; }
[Required]
public int CreatedByUserId { get; set; }
[Required]
public virtual DateTime? DocumentDate { get; set; }
[Required]
public String ReferenceNumber { get; set; }
}
[Table("SalesOrders")]
public class SalesOrder : SalesDocumentHeader
{
[Required]
public String CustomerOrderNumber { get; set; }
public DateTime? DeliverBy { get; set; }
public virtual SortableBindingList<SalesOrderLine> Lines { get; set; }
}
public abstract class LoggedEntity
{
public int Id { get; set; }
public Guid RowId { get; set; }
[ConcurrencyCheck]
public int RowVersionId { get; set; }
}
The context contains
public DbSet<SalesOrder> SalesOrders { get; set; }
public DbSet<SalesDocumentHeader> SalesDocumentHeaders { get; set; }
The SalesDocumentHeader table creates with a Discriminator column. What am I doing wrong?
it makes no difference whether SalesDocumentHeader is declared as abstract or not
because I had another class which inherited from SalesDocumentHeader which I forgot to mark with the table attribute

EF5 Inheritance with code first

I've multiple smaller versions of classes that maps to single database table
e.g
UserBrief Class:
[Table("Users")]
public partial class UserBrief
{
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
UserAdmin Class
[Table("Users")]
public partial class UserAdmin : UserBrief
{
public int RoleID { get; set; }
}
UserHR Class
[Table("Users")]
public partial class UserHR : UserBrief
{
public string EmailAddress { get; set; }
public string Phone { get; set; }
}
User Class
[Table("Users")]
public partial class User
{
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int RoleID { get; set; }
public string EmailAddress { get; set; }
public string Phone { get; set; }
}
I've multiple bounded contexts. Depending on functionality of context I've used above classes.
If I add single class in context and Ignore all other classes then it works fine.
e.g
public DbSet<UserHR> UserHRs { get; set; }
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Ignore<UserBrief>();
modelBuilder.Ignore<UserAdmin >();
modelBuilder.Ignore<User>();
}
Now if I added UserBrief and UserHRs
It gives error "Invalid column name 'Discriminator'" as EF assumes that this is Table per Hierarchy (TPH) approach.
I've been searching for solution, but can't find how to do this.
Any ideas?
Thanks in advance.
The inherited classes in the POCO objects for the TPH approach should represent sub-types of the class, not just property sections. Having the User table which is a combination of UserHR and UserAdmin breaks this representation.
You could attempt to add a Discriminator property to the User table to fix the error, but I would suggest either just using the Users table with nullable properties or modeling your objects as 1-to-1 relationships:
public class UserBrief
{
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual UserAdmin UserAdmin { get; set; }
public virtual UserHR UserHR { get; set; }
}
public class UserAdmin
{
[Key]
[ForeignKey("UserBrief")]
public int EmployeeID { get; set; }
public int RoleID { get; set; }
public virtual UserBrief UserBrief{ get; set; }
}
public class UserHR
{
[Key]
[ForeignKey("UserBrief")]
public int EmployeeID { get; set; }
public string EmailAddress { get; set; }
public string Phone { get; set; }
public virtual UserBrief UserBrief{ get; set; }
}

Resources