I've this base class that contains list of other classes
public class Blacklist
{
public int Id { get; set; }
public virtual IEnumerable<Card> Cards { get; set; }
}
Where Card class looks like
public class Card
{
public int Id { get; set; }
public string Cuid { get; set; }
public int BlacklistId { get; set; }
}
Then I have implemented a derived class that extends Blacklist class
public class BlacklistTwo : Blacklist
{
public new IEnumerable<CardTwo> Cards { get; set; }
}
where CardTwo class extends the base Card class
The problem occurs when I try to invoke a method that accept the base class as parameter with the derived instance. The type of outer class is alright but type of cards stays implemented as base class .
Example:
Insert(
new BlacklistTwo(){
Id = 1,
Cards = new List<CardsTwo>()
{ new CardTwo() { Id = 123123, Cuid = "123213", BlacklistId = 1}});
public void Insert(Blacklist blacklist)
{
blacklist.GetType(); // returns BlacklistTwo
blacklist.Cards.GetType(); // returns IEnumerable<Card> insted of IEnumerable<CardTwo>
}
It works when I set the parameter of method to dynamic but I would like to avoid it if possible.
As pointed out in comments - you don't actually override the property since you use the 'new' keyword. I think this may be what you are trying to achive:
public interface ICard
{
int CardId { get; set; }
string Cuid { get; set; }
int BlacklistId { get; set; }
//.. Other methods and properties
}
public class Card : ICard
{
public int CardId { get; set; }
public string Cuid { get; set; }
public int BlacklistId { get; set; }
}
public class CardTwo : ICard
{
public int CardId { get; set; }
public string Cuid { get; set; }
public int BlacklistId { get; set; }
}
public class Blacklist
{
public int Id { get; set; }
public virtual IEnumerable<ICard> Cards { get; set; }
}
public class BlacklistTwo : Blacklist
{
public override IEnumerable<ICard> Cards { get; set; }
}
And then:
public Test()
{
ICard card1 = new Card();
card1.CardId = 123123;
card1.Cuid = "123213";
card1.BlacklistId = 1;
ICard card2 = new CardTwo();
card2.CardId = 123123;
card2.Cuid = "123213";
card2.BlacklistId = 1;
Insert(new BlacklistTwo()
{
Id = 1,
Cards = new List<ICard>() { card1 ,card2 }
});
if (card1 is Card c1)
{
//Yes - this is a type of Card
}
if (card2 is CardTwo c2)
{
//Yes - this is a type of CardTwo
}
}
You could use an interface or an abstract class, and and probably even avoid extending the blacklist class
Related
Profile.cs
public class TestConfigProfile : Profile
{
public TestConfigProfile()
{
CreateMap<BaseBO, BaseVO>();
CreateMap<A_BO, A_VO>();
CreateMap<SubBO1, SubVO1>();
}
public class A_BO
{
public BaseBO Sub { get; set; }
}
public class A_VO
{
public BaseVO Sub { get; set; }
}
public class BaseBO
{
public int Id { get; set; }
public string Name { get; set; }
}
public class BaseVO
{
public int Id { get; set; }
public string Name { get; set; }
}
public class SubBO1 : BaseBO
{
public int Size { get; set; }
}
public class SubVO1 : BaseVO
{
public int Size { get; set; }
}
}
test code like this...
public void TestConvert()
{
TestConfigProfile.A_BO bo = new TestConfigProfile.A_BO();
bo.Sub = new TestConfigProfile.SubBO1()
{
Id = 1,
Name = "SubBO1",
Size = 4421
};
TestConfigProfile.A_VO vo = _mapper.Map<TestConfigProfile.A_BO, TestConfigProfile.A_VO>(bo);
}
The result is as follows, but it does not meet my expectations, how can I configure this? Also I don't want to use a parent class.
Successfully mapped to a subclass.
With AutoMapper, mapping inheritance is opt-in.
Therefore, when you map from BaseBO to BaseVO, you need to include the derived mappings.
public TestConfigProfile()
{
CreateMap<BaseBO, BaseVO>()
.Include<SubBO1, SubVO1>(); // Include necessary derived mappings
CreateMap<A_BO, A_VO>();
CreateMap<SubBO1, SubVO1>();
}
See this working example.
I want to create a method that will create a List of generic objects. Is it possible? Something like this:
public class Mtrl
{
public string Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Aa { get; set; }
}
public class Trdr
{
public string Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Address { get; set; }
public string AFM { get; set; }
public string Phone01 { get; set; }
public string Aa { get; set; }
}
And then with a generic class to create my list:
public class GenericClass<T>
{
public List<T> GetData<T>()
{
List<T> myList = new List<T>();
if (typeof(T) == typeof(Trdr))
{
myList.Add(new Trdr());//Error 1: cannot convert from Trdr to 'T'
}
if (typeof(T) == typeof(Mtrl))//Error 2: cannot convert from Mtrl to 'T'
{
myList.Add(new Mtrl());
}
return myList;
}
}
My mistake. I will try to clarify more. The Classes Trdr,Mtrl etc will have many different properties. The Getdata method will take data from a web service via json and i want to create a List of Objects and return it
Something like this:
public List<T> GetData<T>()
{
List<T> myList = new List<T>();
if (typeof(T) == typeof(Trdr))
{
for (int i = 0; i < 100; i++)//fetch data from web api in json format
{
Trdr NewObj = new Trdr();
NewObj.Aa = "...";
NewObj.AFM = "...";
myList.Add(NewObj);
}
}
if (typeof(T) == typeof(Mtrl))
{
for (int i = 0; i < 100; i++)
{
Mtrl NewObj = new Mtrl();
NewObj.Aa = "...";
NewObj.Name = "name ...";
myList.Add(NewObj);
}
}
return myList;
}
}
I suggest extracting an interface (or even a base class):
//TODO: Since you have more than 2 classes, please check the common interface
public interface Idr {
string Id { get; set; }
string Name { get; set; }
string Code { get; set; }
string Aa { get; set; }
}
With all classes of interest implementing it:
public class Mtrl : Idr
{
public string Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Aa { get; set; }
}
public class Trdr : Idr
{
public string Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Aa { get; set; }
public string Address { get; set; }
public string AFM { get; set; }
public string Phone01 { get; set; }
}
Now you can use List<Idr> collection; we want the class (T) that implements Idr to have a parameterless constructor as well (new()):
public class GenericClass<T> where T : Idr, new()
{
public List<T> GetData()
{
List<T> myList = new List<T>() {
new T();
};
return myList;
}
}
Sounds like you are trying to create a new list that contains some initial data, and you need to do this for many different types T.
If Mtrl and Trdr has nothing in common and are handled completely differently, consider simply using different methods to get each type of list:
GetDataMtrl(){
var result = new List<Mtrl>();
result.Add(new Mtrl());
return result;
} // etc
Otherwise what you need is Type Constraints of Generic Parameters, that can tell the compiler more about what T is. Or rather what the different values of T must have in common. For example you can do
public List<T> GetData<T>() where T : new()
{
List<T> myList = new List<T>();
myList.Add(new T());
return myList;
}
To say that for T it has to be possible to do new T(). Then you can say GetData<Trdr>() to get a list that contains a single empty Trdr, as you code might seem to try to do.
Maybe you need to set some default values in the data. I notice the classes has a lot of variables in common. Then you might consider using inheritance to specify this commonality:
public class Mtrl
{
public string Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Aa { get; set; }
}
public class Trdr : Mtrl
{
public string Address { get; set; }
public string AFM { get; set; }
public string Phone01 { get; set; }
}
And then write generic code where T is either of the type Mtrl or its descendant class:
public List<T> GetData<T>() where T : Mtrl
{
List<T> myList = new List<T>();
T MtrlOrTrdr = new T();
MtrlOrTrdr.Id = "my-new-id-";
myList.Add(MtrlOrTrdr);
return myList;
}
I have a Json class "GetAllDevices()". My JSON response consists of an Array/List of objects, where each object has the below common properties.
public class GetAllDevices
{
[JsonProperty("_id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("actions")]
public Action[] Actions { get; set; }
public class Action
{
public string _id { get; set; }
public Action_Def action_def { get; set; }
}
public class Action_Def
{
public string _id { get; set; }
public string name { get; set; }
}
}
I want to create 2 generic lists containing all the above properties based on its "type".
lstfoo1 List contains all the properties(_id, name type and actions) where type="foo1". Similarly, lstfoo2 is a List which contains the above properties where type="foo2".
What I have done so far:
string strJson=getJSON();
Foo1 lstfoo1=new Foo1();
Foo2 lstfoo2=new Foo2();
List<Foo1> foo1list= lstfoo1.GetDeviceData(strJson);
List<Foo2> foo2list = lstfoo2.GetDeviceData(strJson);
public class AllFoo1: GetAllDevices
{
}
public class AllFoo2: GetAllDevices
{
}
public abstract class HomeDevices<T>
{
public string type { get; set; }
public string _id { get; set; }
public List<AllFoo1> lstfoo1{ get; set; }
public List<AllFoo2> lstfoo2{ get; set; }
public abstract List<T> GetDeviceData(string jsonResult);
}
public class Foo1: HomeDevices<AllFoo1>
{
public Foo1()
{
type = "foo1";
}
public override List<AllFoo1> GetDeviceData(string jsonResult)
{
var lst =Newtonsoft.Json.JsonConvert.DeserializeObject<List<AllFoo1>>(jsonResult);
var lst1 = lst.Where(x => x.Type.Equals(type)).ToList();
return lst1;
}
}
public class Foo2: HomeDevices<AllFoo2>
{
public Foo2()
{
type = "foo2";
}
public override List<AllFoo2> GetDeviceData(string jsonResult)
{
var lst = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AllFoo2>>(jsonResult);
var lst1 = lst.Where(x => x.Type.Equals(type)).ToList();
return lst1;
}
}
My question is, is there an easier way to do this using abstract classes? Can I directly convert my "GetAllDevices" class into an abstract class and inherit it and deserialize into it and create a generic list?
This should help, if I understand your problem correctly. Let me know if you have questions or it doesn't work as you need. I put this together really quickly without testing.
The way the Type property is defined could be improved but I left it as you had it.
public class MyApplication
{
public void DoWork()
{
string json = getJSON();
DeviceTypeOne foo1 = new DeviceTypeOne();
DeviceTypeTwo foo2 = new DeviceTypeTwo();
IList<DeviceTypeOne> foo1Results = foo1.GetDeviceData(json); // calls GetDeviceData extension method
IList<DeviceTypeTwo> foo2Results = foo2.GetDeviceData(json); // calls GetDeviceData extension method
}
}
// implemented GetDeviceData as extension method of DeviceBase, instead of the abstract method within DeviceBase,
// it's slightly cleaner than the abstract method
public static class DeviceExtensions
{
public static IList<T> GetDeviceData<T>(this T device, string jsonResult) where T : DeviceBase
{
IEnumerable<T> deviceDataList = JsonConvert.DeserializeObject<IEnumerable<T>>(jsonResult);
IEnumerable<T> resultList = deviceDataList.Where(x => x.Type.Equals(typeof(T).Name));
return resultList.ToList();
}
}
// abstract base class only used to house common properties and control Type assignment
public abstract class DeviceBase : IDeviceData
{
protected DeviceBase(string type)
{
if(string.IsNullOrEmpty(type)) { throw new ArgumentNullException(nameof(type));}
Type = type; // type's value can only be set by classes that inherit and must be set at construction time
}
[JsonProperty("_id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("type")]
public string Type { get; private set;}
[JsonProperty("actions")]
public DeviceAction[] Actions { get; set; }
}
public class DeviceTypeOne : DeviceBase
{
public DeviceTypeOne() : base(nameof(DeviceTypeOne))
{
}
}
public class DeviceTypeTwo : DeviceBase
{
public DeviceTypeTwo() : base(nameof(DeviceTypeTwo))
{
}
}
// implemented GetAllDevices class as IDeviceData interface
public interface IDeviceData
{
string Id { get; set; }
string Name { get; set; }
string Type { get; }
DeviceAction[] Actions { get; set; }
}
// renamed and relocated class Action to DeviceAction
public class DeviceAction
{
public string Id { get; set; }
public DeviceActionDefinition DeviceActionDefinition { get; set; }
}
// renamed and relocated Action_Def to DeviceActionDefinition
public class DeviceActionDefinition
{
public string Id { get; set; }
public string Name { get; set; }
}
It should be simple enough to move the implementation of method GetDeviceData() to the base class.
For this to work, you will need to add a constraint on T so the compiler knows a bit more about the base type. You will also need to implement a constructor to populate the concrete type's type string you use around. This is a necessary measure to ensure the value is always populated as it is used for comparison in the method in question:
public abstract class HomeDevices<T> where T: GetAllDevices
{
public HomeDevices(string concreteType)
{
type = concreteType;
}
public string type { get; set; }
public string _id { get; set; }
public List<AllFoo1> lstfoo1 { get; set; }
public List<AllFoo2> lstfoo2 { get; set; }
//This method is now generic and works for both.
public List<T> GetDeviceData(string jsonResult)
{
var lst = Newtonsoft.Json.JsonConvert.DeserializeObject<List<T>>(jsonResult);
var lst1 = lst.Where(x => x.Type.Equals(type)).ToList();
return lst1;
}
}
I hope that helps.
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
I'm working on an entity framework project and I'm trying to form a generic structure for adding joins to my table.
class BrowseCONTACTS_BASE : MyBrowseFrm<CONTACTS_BASE>
{
public BrowseCONTACTS_BASE()
{
MyInitialize();
}
public void MyInitialize()
{
//Here I may have more joins
MyAddJoins<ORDERS>("CONTACTS_BASE", "CB_REFNO", "ORDERS", "OR_REFNO", "OR_REFNO");
}
}
On the parent class MyBrowseFrm
partial class MyBrowseFrm<TEntity>:Form where TEntity:class
{
}
I have the following:
MyAddJoins Function that I call from the child class above
protected void MyAddJoins<TTable>(string pParent, string pParentKey, string pChild, string pChildKey,
string pDisplayField) where TTable:class, new()
{
var a = new TTable();
var item = new MyJoins<dynamic>
{
Parent = pParent,
Child = pChild,
ParentKey = pParentKey,
ChildKey = pChildKey,
DisplayField = pDisplayField,
ChildTable = a
};
MyBdJoins.Add(item);
}
//A list to store Joins added from the child table
private List<MyJoins<dynamic>> MyBdJoins;
protected struct MyJoins<TTable> where TTable : class
{
public string Parent;
public string ParentKey;
public string Child;
public string ChildKey;
public string DisplayField;
public TTable ChildTable;
}
Ok this is the part where I'm stuck, The following code will run when I press the search button.
private void MyGenerateQuery()
{
//Here I cast my Context to CONTACTS_BASE
var loContext = (DbSet<TEntity>)Context.GetPropValue(boName);
foreach (var join in MyBdJoins)
{
loContext
.Join(
(DbSet<ORDERS>)Context.GetPropValue(join.Child),
par => par.GetPropValue(join.ParentKey),
chld => chld.GetPropValue(join.ChildKey),
(par, chld) => new { GetPropValue = chld.GetPropValue(join.DisplayField) }
);
}
myGridView1.DataSource = loContext.ToList();
}
The code above at the part where it is:
(DbSet<ORDERS>)Context.GetPropValue(join.Child)
Here what I want to do is:
(DbSet<TTable>)Context.GetPropValue(join.Child)
of course, the above code gives me an error.
Note: in my code TEntity is CONTACTS_BASE and TTable is ORDERS
so how do I cast this object to type TTable
where it is in MyJoins Structure
public TTable ChildTable;
EDIT:
public partial class ORDERS
{
public int OR_REFNO { get; set; }
public string OR_PROD_CODE { get; set; }
public Nullable<DateTime> OR_DATE { get; set; }
public Nullable<int> OR_M_REFNO { get; set; }
public virtual CONTACTS_BASE CONTACTS_BASE { get; set; }
public virtual ORDER_TYPES ORDER_TYPES { get; set; }
}
public partial class CONTACTS_BASE
{
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public CONTACTS_BASE()
{
this.ORDERS = new List<ORDERS>();
}
public int CB_REFNO { get; set; }
public string CB_NAME { get; set; }
public string CB_ID_NO { get; set; }
public string CB_AGE { get; set; }
public Nullable<decimal> CB_TEL_NO { get; set; }
public string CB_EMAIL { get; set; }
public Nullable<DateTime> CB_ENROLL_DATE { get; set; }
public Nullable<DateTime> CB_START_DATE { get; set; }
public Nullable<DateTime> CB_END_DATE { get; set; }
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual IList<ORDERS> ORDERS { get; set; }
}