Instantiate the field of an Automatic propertiy automatically in C# - c#

this is my Model:
public class Schoolclass
{
private List<Pupil> _pupils;
public Schoolclass()
{
_pupils = new List<Pupil>();
}
public int SchoolclassId { get; set; }
public string SchoolclassCode { get; set; }
public List<Pupil> Pupils
{
get { return _pupils;}
set { _pupils = value; }
}
}
Can I do this somehow with C# only without 3rd-party tools:
[Initialize]
public List<Pupil> Pupils {get;set}
I want that C# generates the field _pupils automatically.

There is no automatic way, but you can still assign the property in the constructor:
public Schoolclass()
{
Pupils = new List<Pupil>();
}
Also, since Pupils is a collection, I would suggest making it read-only:
public List<Pupil> Pupils {get; private set;}
Update
Full class would look like so:
public class Schoolclass
{
public Schoolclass()
{
Pupils = new List<Pupil>();
}
public int SchoolclassId { get; set; }
public string SchoolclassCode { get; set; }
public List<Pupil> Pupils { get; private set; }
}

Related

Project a name-value list into an object

I want to be able to save an arbitrary flat object into the name-value list.
public class NameValueListEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[InverseProperty(nameof(NameValueListContentEntity.Entity))]
public ICollection<NameValueListContentEntity> Content { get; set; }
}
public class NameValueListContent
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("entity_fk")]
public NameValueListEntity Entity { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
public class ObjectToSave
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
I could use reflection to manually assemble/parse the list, but it will create a lot of overhead. Lots of NameValueListContent objects will be needlessly created both during the saving and the reading. Could it somehow be omitted? Especially during the reading, which is very performance-sensitive in my case.
Assume you have a AppDbContext class that holds your NameValueListContent class objects named as NVListContents. You can read and write the name-value list of objects by doing the following:
public class AppDbContext : DbContext
{
public DbSet<NameValueListContent> NVListContents { get; set; }
public AppDbContext()
: base()
{ }
}
public class SomeClass
{
private AppDbContext context { get; set; }
public SomeClass(AppDbContext _context)
{
context = _context;
}
public List<ObjectToSave> ReadObjects()
{
return context.NVListContents
.Select(nvlc => new ObjectToSave { Prop1 = nvlc.Name, Prop2 = nvlc.Value
}).ToList();
}
public bool WriteObjects(int id, string name, string value)
{
var query = context.NVListContents
.FirstOrDefault(nvlc => nvlc.Id == id);
if(query != null)
{
query.Name = name;
query.Value = value;
context.Update(query);
context.SaveChanges();
return true;
}
else
{
return false;
}
}
}
Hope, this answers to your question.

Update list values after update root class object

I have the following classes:
public class Class_A
{
public string my_field { get; set; }
public int id { get; set; }
// etc...
}
public class Class_B
{
public string my_field { get; set; }
public Class_A field_A { get; set; }
// etc...
}
public class Class_C
{
public string my_field { get; set; }
public Class_A field_A { get; set; }
// etc...
}
List<Class_A> list_A = new List<Class_A>(); //and then populate it
List<Class_B> list_B = new List<Class_B>(); //and then populate it
List<Class_C> list_C = new List<Class_C>(); //and then populate it
And then, when I update some element of list_A, for example
Class_A old_a, new_a;
old_a = list_A.Where("some condition").FirstOrDefault();
new_a = new Class_A();//and then initialize it
list_A[list_A.FindIndex(x => x.Equals(old_a))] = new_a;
I need, that all elements of list_B and list_C, which field Class_A equals old_a will be update to new_a.
1. What is the best way to do this? Now I have following variant, but I think, that it's could be better:
list_B.Where(x => x.Class_A.Equals(old_a)).ForEach(x => x.Class_A = new_a);
2. What is the best way to update all values, if I'll have this code?
public class Class_D
{
public string my_field { get; set; }
public List<Class_A> list_A { get; set; }
// etc...
}
List<Class_D> list_D = new List<Class_D>(); //and then populate it
Have a look at ObservableCollection and Item PropertyChanged
You can make from your list_A an observable collection when can be received by Class_B and Class_C.

How to change constructor of a class to recieve generic list of objects of already created class and constructor? (C#)

I have the following class:
public class OrderArticlesAdapter : RecyclerView.Adapter
{
public List<OrderArticleViewModel> listOfOrderArticles;
.....
.....
//constructor
public OrderArticlesAdapter(List<OrderArticleViewModel> orderArticles, ....., .....)
{
listOfOrderArticles = orderArticles;
......
}
}
I want the class to be able to work not only with list of OrderArticleViewModel but also with list of type Invoices and any other type. OrderArticleViewModel class looks like that:
public class OrderArticleViewModel
{
public string ArticleId { get; set; }
public string LotId { get; set; }
public string ArticleName { get; set; }
public string PriceDiscount { get; set; }
public string ArticlePrice { get; set; }
public string ArticleQuantity { get; set; }
public string ArticleTotalPrice { get; set; }
public string Barcode { get; set; }
public string ExpireDate { get; set; }
public string LotName { get; set; }
public string ArticlePriceAfterDiscount
{
get
{
decimal priceDiscount;
if (!Decimal.TryParse(PriceDiscount, out priceDiscount))
{
priceDiscount = 0;
}
decimal articlePrice = Convert.ToDecimal(ArticlePrice);
decimal discountAmount = Math.Round(articlePrice * (priceDiscount / 100), 4);
decimal articlePriceAfterDiscount = articlePrice - discountAmount;
return articlePriceAfterDiscount.ToString();
}
}
}
Invoices class looks like that:
public class Invoices
{
public string ArtId { get; set; }
public string Name { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
public string Sum { get; set; }
public string Discount { get; set; }
public string PriceWodiscount { get; set; }
public string Id { get; set; }
}
ArticleId , ArticleName, ArticleQuantity, PriceDiscount, ArticlePrice, Discount, ArticlePriceAfterDiscount from class OrderArticleViewModel correspond to properties ArtId, Name, Quantity, Discount, Price, Sum from class Invoices. How do I make OrderArticlesAdapter constructor to be able to recieve generic list of OrderArticleViewModel or Invoices or any other type without breaking the functionality of the code where I already have used instance of OrderArticlesAdapter?
Create another constructor in which you convert the invoice list to an ArticleViewModel list:
public class OrderArticlesAdapter : RecyclerView.Adapter
{
public List<OrderArticleViewModel> listOfOrderArticles;
public OrderArticlesAdapter(List<OrderArticleViewModel> orderArticles, ....., .....)
{
listOfOrderArticles = orderArticles;
}
public OrderArticlesAdapter(List<Invoice> invoices)
{
listOfOrderArticles = invoices.Select(MapToArticleVM).ToList();
}
private OrderArticleViewModel MapToArticleVM(Invoice invoice)
{
return new OrderArticleViewModel
{
ArticleId = invoice.ArtId,
// ...
};
}
}
Do note the resulting list will miss some properties, because Invoice doesn't contain Barcode, for example.
One option would be to write an extension method to convert an invoice to view model
public static class InvoicesExtensions
{
public static OrderArticleViewModel ToOrderArticleViewModel(this Invoices i)
{
return new OrderArticleViewModel { ArticleId = i.ArtId, ... };
}
}
... and then you can call the constructor like
var invoices = new List<Invoices>();
var adapter = new OrderArticlesAdapter(invoices.Select(i => i.ToOrderArticleViewModel()).ToList());
I would also recommend
renaming Invoices to Invoice as it seems to represent an actual invoice not multiple invoices
use IEnumerable<OrderArticleViewModel> instead of List<OrderArticleViewModel> for the constructor parameter as this makes the constructor more versatile

Ignore Mapping of inner list property in AutoMapper --EF6,C#

I have a collection property of DTO like this
public ICollection<Applicant> Applicants{get;set;}
Applicant Model
public class Applicant
{
public int Id{get;set;}
public string name{get;set;}
public ICollection<ApplicantSkillsVM> ApplicantSkills { get; set; }
}
public class ApplicantSkillsVM
{
public int Id {get;set;}
public Skill skill{get;set;}
}
I want to map my List<iApplicant> DTO to entity given that I want to take ApplicantSkillsVM but ignore skill inside ApplicantSkillsVM.
I have a model which is list List<Applicant> and that contains another list List<ApplicantSkillsVM> and ApplicantSkillsVM has a property skill. I want to ignore this (skill) while mapping. Its simple.
How can I do this in latest the AutoMapper version with EF6?
Here a running sample:
internal class Program
{
#region Methods
private static void Main(string[] args)
{
// Configure the mappings
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ApplicantSkillVM, ApplicantSkill>().ForMember(x => x.Skill, x => x.Ignore()).ReverseMap();
cfg.CreateMap<ApplicantVM, Applicant>().ReverseMap();
});
var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
var mapper = config.CreateMapper();
ApplicantVM ap = new ApplicantVM
{
Name = "its me",
ApplicantSkills = new List<ApplicantSkillVM>
{
new ApplicantSkillVM {SomeInt = 10, SomeString = "test", Skill = new Skill {SomeInt = 20}},
new ApplicantSkillVM {SomeInt = 10, SomeString = "test"}
}
};
List<ApplicantVM> applicantVms = new List<ApplicantVM> {ap};
// Map
List<Applicant> apcants = Mapper.Map<List<ApplicantVM>, List<Applicant>>(applicantVms);
}
#endregion
}
/// Your source classes
public class Applicant
{
#region Properties
public List<ApplicantSkill> ApplicantSkills { get; set; }
public string Name { get; set; }
#endregion
}
public class ApplicantSkill
{
#region Properties
public Skill Skill { get; set; }
public int SomeInt { get; set; }
public string SomeString { get; set; }
#endregion
}
// Your VM classes
public class ApplicantVM
{
#region Properties
public List<ApplicantSkillVM> ApplicantSkills { get; set; }
public string Description { get; set; }
public string Name { get; set; }
#endregion
}
public class ApplicantSkillVM
{
#region Properties
public Skill Skill { get; set; }
public int SomeInt { get; set; }
public string SomeString { get; set; }
#endregion
}
public class Skill
{
#region Properties
public int SomeInt { get; set; }
#endregion
}
}
Initially my model ApplicantSkillsVM didnt have reference Id for Skill which should be nullable
So my model had to look like
public class ApplicantSkillsVM{
public int Id {get;set;}
public int? skillId{get;set;} //updated property
public Skill skill{get;set;}
}
The problem resolved

Inconsistent Accessibility: Property Type Error

I've done the googling to no avail. This is the one sole error preventing my code from compiling and running but I can't seem to figure it out. The exact text of the error is "...Dictionary is less accessible than property FleetAirliner.InsuranceProperties"
Any ideas what could be causing this?
namespace TheAirline.Model.AirlinerModel
{
[Serializable]
public class FleetAirliner
{
public Airliner Airliner { get; set; }
public string Name { get; set; }
public Airport Homebase { get; set; }
public enum PurchasedType { Bought, Leased,BoughtDownPayment }
public DateTime PurchasedDate { get; set; }
public PurchasedType Purchased { get; set; }
public Boolean HasRoute { get { return this.Routes.Count > 0; } set { ;} }
public AirlinerStatistics Statistics { get; set; }
/*Changed for deleting routeairliner*/
public enum AirlinerStatus { Stopped, On_route, On_service, Resting, To_homebase, To_route_start }
public AirlinerStatus Status { get; set; }
public Coordinates CurrentPosition { get; set; }
public List<Route> Routes { get; private set; }
public Flight CurrentFlight { get; set; }
public DateTime GroundedToDate { get; set; }
public List<Pilot> Pilots { get; set; }
public Dictionary<string, AirlinerInsurance> InsurancePolicies { get; set; } //error occurs here
public int NumberOfPilots {get {return this.Pilots.Count;} private set {;}}
public FleetAirliner(PurchasedType purchased,DateTime purchasedDate, Airline airline,Airliner airliner,Airport homebase)
{
this.Airliner = airliner;
this.Purchased = purchased;
this.PurchasedDate = purchasedDate;
this.Airliner.Airline = airline;
this.Homebase = homebase;
this.Name = airliner.TailNumber;
this.Statistics = new AirlinerStatistics(this);
this.Status = AirlinerStatus.Stopped;
this.CurrentPosition = new Coordinates(this.Homebase.Profile.Coordinates.Latitude, this.Homebase.Profile.Coordinates.Longitude);
this.Routes = new List<Route>();
this.Pilots = new List<Pilot>();
this.InsurancePolicies = new Dictionary<string, AirlinerInsurance>();
}
It means that class "AirlinerInsurance" Is not Public.
It is a property that is public, but other classes, that are allowed to use the property, might not have access rights to the class itself (it is private / internal).
Edit
Now that you have posted the code of class "AirlinerInsurance", just add a "public" modifier to it.
You can read more about it here and here
you need
class AirlinerInsurance {
// stuff
}
to be
public class AirlinerInsurance {
//stuff
}

Categories

Resources