I have a generic UOW repository pattern. I need to a add a few entities which will have the same properties but the names will differ from each other. Is there any easiest way to access the repositories without having to instantiate each and every entity repository separately.
Here is an example code of the entity structure.
public int Id { get; set; }
public string UserId { get; set; }
public int ProductId { get; set; }
public int OrderedQuantity { get; set; }
public int FreeQuantity { get; set; }
public double TotalPrice { get; set; }
public double DiscountOffered { get; set; }
public double TotalBilled { get; set; }
Entities can be like AbcProduct / XyzProduct / MnoProduct etc. they will be about 10-12 different entities of such products and cannot be kept under a single table with CategoryId. These tables will be often used and updated multiple times in the database which is why we would like to go with this approach.
Thanks in advance for the help.
You can make them share a common interface.
public interface IProduct
{
public int Id { get; set; }
public string UserId { get; set; }
public int ProductId { get; set; }
public int OrderedQuantity { get; set; }
public int FreeQuantity { get; set; }
public double TotalPrice { get; set; }
public double DiscountOffered { get; set; }
public double TotalBilled { get; set; }
}
As long as AbcProduct, XyzProduct and MnoProduct implement that interface, you can use a generic repository of that interface type
GenericRepository<IProduct> genericRepository;
var abcProduct = new AbcProduct();
var xyzProduct = new XyzProduct();
var mnoProduct = new MnoProduct();
genericRepository.Add(abcProduct);
genericRepository.Add(xyzProduct);
genericRepository.Add(mnoProduct);
Of course you can use inheritance. Use an abstract class as base class.
public abstract class Product
{
public abstract int Id { get; set; }
public abstract string UserId { get; set; }
public abstract int ProductId { get; set; }
public abstract int OrderedQuantity { get; set; }
public abstract int FreeQuantity { get; set; }
public abstract double TotalPrice { get; set; }
public abstract double DiscountOffered { get; set; }
public abstract double TotalBilled { get; set; }
}
and then derives other products
public class abcProduct:Product
{
public override int Id { get; set; }
...
}
Related
<I have two classes with too many fields . which are basically the Model of MVC . I want to create a third class which take few fields from both 1st,2nd by inheritance but not all the fields of 1st and 2nd class is it possible by inheritance .I want to
make a new class without declare field in it
public class OpeningBalanceLiteModel
{
public Int64 LedgerId { get; set; }
public String LedgerCode { get; set; }
public Int64? ParentLedgerId { get; set; }
public Decimal OpeningBalance { get; set; }
public Boolean? Status { get; set; }
public Int32? LedgerCategoryId { get; set; }
public Byte Is_Active { get; set; }
public Byte Is_Deleted { get; set; }
}
public class DrCrDetailLiteModel
{
public Int32 Id { get; set; }
public Int32 TransactionTypeId { get; set; }
public Int32? AmountType { get; set; }
public Decimal? Amount { get; set; }
public String VoucherNarration { get; set; }
public Int32 FinancialYearId { get; set; }
public Int64 CompanyId { get; set; }
public Decimal? SubsidiaryId { get; set; }
public Decimal? LocationBranchId { get; set; }
public Decimal? DivisionId { get; set; }
public Int32? DepartmentId { get; set; }
public Int32? ProjectId { get; set; }
public Int32? ProjectEstimationId { get; set; }
public Boolean? IsAdvancePayment { get; set; }
public Boolean? IsHiddenFromSourceLedger { get; set; }
public Boolean? IsReversed { get; set; }
}
public class OpeningBalanceDrCrMurg
{
}```
* i wan to add 3 fields of both class by inheritance
We commonly calls inheritance a "is a" relation ship, an apple is a fruit. If you do not include all properties it is not a "is a" relationship. Is all fruits have a color, then an apple must have a color.
Moreover, c# does not support multiple inheritance. You could inherit from multiple interfaces, and that would also allow you to use explicit interface implementation to hide properties unless a reference of the interface type is used. But I get the impression that your goal is implementation inheritance.
My recommendation would be to use Composition instead of inheritance. Group your properties in to logical groups, and compose these models, for example:
public class LedgerModel{
public Int64 LedgerId { get; set; }
public String LedgerCode { get; set; }
public Int64? ParentLedgerId { get; set; }
}
public class OpeningBalanceLiteModel{
LedgerModel {get;set;}
...
}
That should allow finer grained control to allow you to include any combination of property-groups in your classes.
you should create a Base Class ex:
public class BaseClass
{
public int Id1 { get; set; }
public int Id2 { get; set; }
public int Id3 { get; set; }
}
public class childrenClass1 :BaseClass
{
...
}
public class childrenClass2:BaseClass
{
...
}
Now children class1 and 2 have Id1/Id2/Id3
I Have This Product Class In My Project
public string Title { get; set; }
public int CategoryId { get; set; }
public int ProductDetailId { get; set; }
public int BrandId { get; set; }
public Gender GenderTypeId { get; set; }
public int ProductCount { get; set; }
public decimal? Price { get; set; }
public double? Discount { get; set; }
public string Description { get; set; }
public DateTime CreateDate { get; set; }
public DateTime? EditDate { get; set; }
public virtual ProductDetail ProductDetail { get; set; }
I Want A ProductDetails Class For Different Products
For Example:
When Customer Select TV Product ProductDetails Shows Width&Height&Inch Or When Selected A T-Shirt It Shows S-L-XL-XXL And So On...
Thanks
You can use inheritance with EF core
First we define the C# class inheritance:
public class Product
{
public string Title { get; set; }
//define the rest of the properties
public int ProductDetailId { get; set; }
public ProductDetails ProductDetails { get; set; }
}
public abstract class ProductDetails
{
public string ProductDetailType { get; set; }
public int Id { get; set; }
}
public class TvDetails : ProductDetails
{
public float Width { get; set; }
public float Height { get; set; }
}
public class ClothDetails : ProductDetails
{
public string Size { get; set; }
}
Now we need to define how to map it with EF core. there are multiple approaches as it says in the documentation I mentioned above.
By default EF core will use Table-per-hierarchy and discriminator.
you can also define the discriminator:
modelBuilder.Entity<ProductDetails>()
.HasDiscriminator(p => p.ProductDetailType );
Now the last problem would be we querying, we can simply cast the object based on the discriminator value.
I'm working on a trucking API using Entity Framework (EF) Core. Basic CRUD operations are working fine using the repository pattern. There is an error in
configurations I am implementing, however.
I want to obtain multiple trailers and trucks associated with single load, reflecting the one-to-many relationship.
public class LoadConfiguration : IEntityTypeConfiguration<Load>
{
public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Load> builder)
{
builder.Property(p=>p.Id).IsRequired();
builder.HasOne(t=>t.Customer).WithMany().HasForeignKey(p=>p.CustomerId);
builder.Property(p=>p.LoadedFrom).IsRequired();
builder.HasMany(p=>p.Trailer).WithOne().HasForeignKey(t=>t.TrailerId);
builder.HasMany(p=>p.Truck).WithOne().HasForeignKey(t=>t.TruckId);
builder.Property(p=>p.Destination).IsRequired();
}
}
public class Truck:BaseEntity
{
public int PlateNo { get; set; }
public string ModelName { get; set; }
public Location StateCode { get; set; }
public int PollutionCertificateValidity { get; set; }
public int DateOfPurchase { get; set; }
public int FitnessCertificateValidity { get; set; }
}
public class Load:BaseEntity
{
public Customer Customer { get; set; }
public int CustomerId { get; set; }
public string LoadedFrom { get; set; }
public Trailer Trailer { get; set; }
public int TrailerId { get; set; }
public Truck Truck { get; set; }
public int TruckId { get; set; }
public string Destination { get; set; }
}
public class Trailer:BaseEntity
{
public int TrailerCapacity { get; set; }
public Truck Truck { get; set; }
public int TruckId { get; set; }
}
public class BaseEntity
{
public int Id { get; set; }
}
A one-to-many relationship is defined by using navigation collections, that has the capacity to hold many Trucks and Trailers. You can choose the collection type freely, but I would suggest ICollection generic type.
Modify your Load class as follows:
public class Load:BaseEntity
{
public Customer Customer { get; set; }
public int CustomerId { get; set; }
public string LoadedFrom { get; set; }
public string Destination { get; set; }
// navigation collections
public ICollection<Trailer> Trailers { get; set; }
public ICollection<Truck> Trucks { get; set; }
}
You will then be able to set up the relationship in your LoadConfiguration class by using
the pluralized name:
builder.HasMany(p=>p.Trailers).WithOne();
builder.HasMany(p=>p.Trucks).WithOne();
.. even though EF Core will be smart enough to figure out the relation by convention so the fluent configuration is redundant.
I am a VB.NET programmer, but I am trying to learn C# and MVC in my spare time. I am using ASP.NET MVC 5.1.0.0 and I am trying to do code-First database creation in a local instance of SQL Server.
I was able to get the first database table to update in the database when I ran Update-Database from within the IDE, but when I added a second table that has a PK/FK relationship with the first, I am getting a red line under [ForeignKey] which reads
Does not contain a constructor that takes 1 arguments
I have been searching all over and not getting anywhere. Any suggestions or help would be appreciated. By the way, the first table is a PK/FK relationship to the AspNetUsers table.
public class BuildDatabase : IdentityUser
{
public virtual Companies Companies { get; set; }
public virtual NotaryProfile NotaryProfile { get; set; }
}
public class Companies
{
[Key]
[Column("CompanyID")] // Did this as the database will reflect TableName_ColumnName instead.
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public bool IsActive { get; set; }
public bool IsNotary { get; set; }
public virtual ICollection<NotaryProfile> NotaryProfile { get; set; }
}
public class NotaryProfile
{
[Key]
public int NotaryID { get; set; }
public string NamePrefix { get; set; }
public string FirstName { get; set; }
public string MiddleInitial { get; set; }
public string LastName { get; set; }
public string NameSuffix { get; set; }
public bool IsActive { get; set; }
public int DefaultState { get; set; }
public int DefaultCounty { get; set; }
public bool IsSigningAgent { get; set; }
public bool HasABond { get; set; }
public decimal BondAmount { get; set; }
public bool HasEandO { get; set; }
public decimal EandOAmount { get; set; }
public bool ElectronicNotarizationsAllowed { get; set; }
public string ElectronicTechnologyUsed { get; set; }
public string ComissionNumber { get; set; }
public DateTime CommissionIssued { get; set; }
public DateTime CommssionOriginal { get; set; }
public DateTime CommissionExpires { get; set; }
public DateTime CommissionFiledOn { get; set; }
public string SOSAuditNumber { get; set; }
public string CommissionDesc { get; set; }
[Foreignkey("CompanyID")] // Companies.CompanyID = PK
public int CompanyID { get; set; } // PK/FK relationship.
public Companies Companies { get; set; } // Reference to Companies table above.
}
public class SchemaDBContext : IdentityDbContext<BuildDatabase>
{
public SchemaDBContext()
: base("DefaultConnection"){}
public DbSet<Companies> Companies { get; set; }
public DbSet<NotaryProfile> NotaryProfile { get; set; }
}
One of your classes (probably NotaryProfile) needs to reference another object (the foreign key relationship) but there is no constructor in that class that accepts an argument to establish that relationship, e.g.:
public NotaryProfile(int companyId) {
this.companyId = companyId;
}
BTW, a better way to establish that relationship is to use the actual class type rather than the ID, as in:
public class NotaryProfile {
...
public Company Company { get; set; }
// Instead of this:
// public int CompanyID { get; set; } // PK/FK relationship.
...
}
See also:
C# “does not contain a constructor that takes '1' arguments”
Does not contain a constructor that takes 2 arguments
Ok dead basic question, I'm a self taught developer so often I seem to have gaps where I can't decide which was is the right way... and this is one of them!! Simple I have a view model which has a collection of child items. But where these classes are defined I can't decide if the child object should be a subclass of the parent...
For example this:
public class ActionChartViewModel
{
public IEnumerable<ActionChartItemViewModel> Items { get; set; }
public TextPagingInfo TextPagingInfo { get; set; }
}
public class ActionChartItemViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Rating { get; set; }
public string Comment { get; set; }
public string AssignedToUserName { get; set; }
public string ContactRequested { get; set; }
public bool Resolved { get; set; }
public int NoteCount { get; set; }
public string ContactDetails { get; set; }
public int ResponseId { get; set; }
}
Or this:
public class ActionChartViewModel
{
public IEnumerable<Item> Items { get; set; }
public TextPagingInfo TextPagingInfo { get; set; }
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Rating { get; set; }
public string Comment { get; set; }
public string AssignedToUserName { get; set; }
public string ContactRequested { get; set; }
public bool Resolved { get; set; }
public int NoteCount { get; set; }
public string ContactDetails { get; set; }
public int ResponseId { get; set; }
}
}
I prefer the second one for a code readability and simplicity front, but I don't know the pros and cons of subclasses. What would you guys think??
Thanks in advance!!
I would use separate classes (in same file) as opposed to an inner class. Inner class would be useful when it serves only the parent class, i.e. would not be accessed from outside of the parent class, only by the parent class methods, etc. In your case the inner class needs to be used on view(s), so I don't see a need for it. The first option, i.e. separate classes, is actually simpler to me and reads better.
"SubClass" is when you create more concrete implementations (inherits) of its types. As # bloparod says, you're doing "inner classes". I also rarely use inner classes. Sometimes I use some private or internal classe as a temporary. If you do that, you will need to create with the sintaxe like:
ActionChartViewModel.Item item = new ActionChartViewModel.Item();
I usually separete files and use public classes but sometimes when I have lots and lots of ViewModel, I think a good pratice is to keep all of the same category of ViewModels on a single file and inherited when necessary, for sample:
File: ProductViewModel.cs
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string CategoryName { get; set; }
}
public class ProductDetailViewModel : ProductViewModel
{
public int Stocke { get; set; }
public string Obs { get; set; }
public IEnumerable<ProductMovViewModel> Inventory
/* other properties */
}
public class ProductMovViewModel
{
public int Id { get; set; }
public DateTime Date { get; set;
public int Amout { get; set; }
}
As a good pratice too you can separete in files your ViewModels, as you prefer.