Pass list from model class to DbInitliazer - c#

I'm new to C#. I'm working on a web app project. I want to know how to initialize the list in my DbInitializer class. For example, this is the Model:
using System;
using System.Collections.Generic;
namespace Manager.Model
{
public class Vendor
{
public int VendorID { get; set; }
public string CardName { get; set; }
public string WebsiteLink { get; set; }
public DateTime PartnerSince { get; set; }
public List<Rep> Reps { get; set; }
public string SupportNo { get; set; }
public string SupportEmail { get; set; }
public string Rebate { get; set; }
public string Spiff { get; set; }
public string Quote { get; set; }
}
public class Rep
{
public string RepName { get; set; }
public string RepPosition { get; set; }
public string RepNo { get; set; }
public string RepEmail { get; set; }
}
}
How would I pass this list in the Initialize method?
public static void Initialize(ManagementContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.Vendors.Any())
{
return; // DB has been seeded
}
var vendors = new Vendor[]
{
new Vendor{CardName="Vendor1", WebsiteLink="www.vendor1.com", PartnerSince=DateTime.Parse("10-10-2012"), SupportNo="521-586-8956", SupportEmail="nikki#vendor1.com"},
};
foreach (Vendor v in vendors)
{
context.Vendors.Add(v);
}
context.SaveChanges();

If you'd like to do everything inline:
Vendor[] vendors = new Vendor[]
{
new Vendor() // first vendor
{
CardName="Vendor1",
WebsiteLink="www.vendor1.com",
PartnerSince=DateTime.Parse("10-10-2012"),
SupportNo="521-586-8956",
SupportEmail="nikki#vendor1.com",
Reps = new List<Rep>()
{
new Rep() // first rep
{
RepName = "name",
RepPosition = "pos",
RepNo = "no",
RepEmail = "email"
}
// , new Rep(){...} // second rep, etc...
}
}
// , new Vendor(){....} // second vendor, etc...
};
Or simply prepare the Reps first:
List<Rep> Reps1 = new List<Rep>(); // Reps 1 for Vendor 1
Reps1.Add(new Rep()
{
RepName = "name",
RepPosition = "pos",
RepNo = "no",
RepEmail = "email"
});
// you may add more rep
then assign it in vendor
Vendor[] vendors = new Vendor[]
{
new Vendor() // first vendor
{
CardName="Vendor1",
WebsiteLink="www.vendor1.com",
PartnerSince=DateTime.Parse("10-10-2012"),
SupportNo="521-586-8956",
SupportEmail="nikki#vendor1.com",
Reps = Reps1
}
// , new Vendor(){....} // second vendor, etc...
};
For question if you change into string[] RepNames,
string[] RepNames1 = new string[]
{
"name1",
"name2" // , etc....
}
then assign it in vendor
Vendor[] vendors = new Vendor[]
{
new Vendor() // first vendor
{
CardName="Vendor1",
WebsiteLink="www.vendor1.com",
PartnerSince=DateTime.Parse("10-10-2012"),
SupportNo="521-586-8956",
SupportEmail="nikki#vendor1.com",
RepNames = RepNames1
}
// , new Vendor(){....} // second vendor, etc...
};

Related

Accessing value by key in property dictionary

Im trying to access and display the value of a dictionary where the dictionary has no real name but is a property of a class.
Currently I have an enum "Roles" with three elements (fighter, rogue, and sorcerer), and:
public class Adventurer
{
public int ID { get; set; }
public string Name { get; set; }
public Roles Role { get; set; }
public List<Skill> Skills { get; set; }
public override string ToString()
{
return $"{ID}" + " - " + $"{Name}" + " - " + $"{Role}";
}
}
and:
public class Skill
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Dictionary<Roles, Skill> LinkedTo { get; set; }
}
and in another class I have:
private void CreateSkills()
{
Skill swordFighting = new Skill() { ID = 1, Name = "Sword fighting"};
Skill stealth = new Skill() { ID = 2, Name = "Stealth"};
Skill magic = new Skill() { ID = 3, Name = "Magic"};
swordFighting.LinkedTo = new Dictionary<Roles, Skill>
{
{ Roles.Fighter, swordFighting }
};
stealth.LinkedTo = new Dictionary<Roles, Skill>
{
{ Roles.Rogue, stealth }
};
magic.LinkedTo = new Dictionary<Roles, Skill>
{
{ Roles.Sorcerer, magic }
};
}
private void DisplaySkills(Adventurer adventurer)
{
adventurer.Skills = adventurer.Role.LinkedTo; // I WOULD LIKE SOMETHING LIKE THIS...
lstAdventurer.ItemsSource = adventurer.Skills;
}
Is there some way of accessing the values (skills) of the adventurer by knowing only the role (fighter/rogue/sorcerer)?
Best,
Dedoj
Would you mean something like this?
for known Roles like Roles.Fighter:
adventurer.Skills = adventurer.Skills
.Select(s => s.LinkedTo.ContainsKey(Roles.Fighter) ? s.LinkedTo[Roles.Fighter] : null)
.Where(s => s != null).ToList();

How do I copy two similar lists?

I have two lists. There are only one field difference. How to fill the lists with each other.
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
}
[Serializable()]
public class Lst2
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
public string filed101 { get; set; }
}
List<Lst1> Lst1_ = new List<Lst1>();
List<Lst2> Lst2_ = new List<Lst2>();
I fill out lists from files.
then,I need to fill out the list two from list one,There are many fields And I do not want to use the foreach loop.
It should be remembered that my previous class was already built and serialized and stored in a file. And now I need to transfer the previous information to the second class structure.
I do not want to use this loop!
foreach (var t in Lst1_)
{
Lst2_.Add(new lst2
{
filed1 = t.filed1,
filed2 = t.filed2,
.
.
.
filed100 = t.filed100,
filed101 = "kk"
}
}
Is this what you want?
class Lst1
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
}
class Lst2
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
public string filed6 { get; set; }
}
void CopyData()
{
// test data
List<Lst1> Lst1_ = new List<Lst1>()
{
new Lst1()
{
filed1 = "1",
filed2 = "2",
filed3 = "3",
filed4 = "4",
filed5 = "5",
},
new Lst1()
{
filed1 = "6",
filed2 = "7",
filed3 = "8",
filed4 = "9",
filed5 = "10",
},
};
List<Lst2> Lst2_ = new List<Lst2>();
foreach (var item in Lst1_)
{
Type type1 = item.GetType();
PropertyInfo[] properties1 = type1.GetProperties();
var current = new Lst2();
Type type2 = current.GetType();
PropertyInfo[] properties2 = type2.GetProperties();
int k = 0;
foreach (PropertyInfo property in properties1)
{
var value = property.GetValue(item, null);
int n;
bool isNumeric = int.TryParse(value.ToString(), out n);
if (!isNumeric)
value = "Your desired value";
properties2[k].SetValue(current, value);
k++;
}
Lst2_.Add(current);
}
}
It copies everything from list 1 to list2.
No need to waste your time and money, AutoMapper can do it for you with only 2 lines of code:
using AutoMapper;
namespace ConsoleApp39
{
class Program
{
static void Main (string[] args)
{
// fill list1 with data
var list1 = new List1
{
Field1 = "test",
Field2 = 5,
Field3 = false,
};
// 1) configure auto mapper
Mapper.Initialize (cfg => cfg.CreateMap<List1, List2> ());
// 2) create list2 and fill with data from list1
List2 list2 = Mapper.Map<List2> (list1);
// fill extra fields
list2.Field4 = new byte[] { 1, 2, 3 };
}
}
public class List1
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
}
public class List2
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
public byte[] Field4 { get; set; } // extra field
}
}
Do Lst1 can inheritance from Lst2?
Something like this,
the two lists:
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public int filed2 { get; set; }
public bool filed100 { get; set; }
}
[Serializable()]
public class Lst2 : Lst1
{
public string filed101 { get; set; }
}
and one print extension
public static class CExtensions
{
public static string PropertyList(this Lst1 obj)
{
var props = obj.GetType().GetProperties();
var sb = new StringBuilder();
foreach (var p in props)
{
sb.AppendLine(p.Name + ": " + p.GetValue(obj, null));
}
return sb.ToString();
}
}
then using it:
class Program
{
static void Main(string[] args)
{
const int I = 15;
try
{
//init first list
List<Lst1> Lst1_ = new List<Lst1>();
Init(Lst1_);
//print it
Console.WriteLine("Lst1_");
Console.WriteLine(new string('-', I));
Lst1_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
//init second list
List<Lst1> Lst2_ = Lst1_.Cast<Lst1>().ToList(); //equivalent of two next lines
//List<Lst1> Lst2_ = new List<Lst2>().ConvertAll(x => (Lst1)x);
//Lst2_.AddRange(Lst1_);
//add one more
Lst2_.Add(new Lst2
{
filed1 = "101",
filed2 = 202,
filed100 = true,
filed101 = "10100"
});
//and print
Console.WriteLine("Lst2_");
Console.WriteLine(new string('-', I));
Lst2_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
private static void Init(List<Lst1> lst_)
{
for (int i = 1; i <= 3; i++)
{
lst_.Add(new Lst1
{
filed1 = i.ToString(),
filed2 = 2 * i,
filed100 = i % 2 == 0
});
}
}
}
enjoy =)

How to use Linq add list data to list sub class?

i want add list data (from class) to sub class list for sent JSON FORMAT to other api.
Class
public class InPaymentDetailResponse
{
public List<InPaymentDetail> Data { get; set; }
}
public class InPaymentDetail
{
public string runningno { get; set; }
public decimal totalpremium { get; set; }
}
public class InformationRequest
{
.....
.....
public List<CreateDetailRequest> _detailData { get; set; }
public ExPaymentRequest _payment { get; set; }
}
public class ExPaymentRequest
{
.....
.....
public ExCashtransaction _cash { get; set; }
}
public class ExCashtransaction
{
public string createby { get; set; }
public DateTime createdate { get; set; }
public List<ExCashtransactionDetailsRequest> details { get; set; }
}
public class ExCashtransactionDetailsRequest
{
public string runningno { get; set; }
public decimal amount { get; set; }
}
Code C#
private async Task<.....> CreateInfo(InformationRequest r)
{
InPaymentDetailResponse resPaymentDetail = new InPaymentDetailResponse();
resPaymentDetail.Data = new List<InPaymentDetail>();
foreach (var item in r._detailData)
{
.....
..... //Process Data
.....
var resPaymentDetailData = new InPaymentDetail
{
//Add List Data To New Object
runningno = item.runningno,
totalpremium = item.totalpremium
};
resPaymentDetail.Data.Add(resPaymentDetailData);
}
HttpResponseMessage response = new HttpResponseMessage();
foreach (var res in resPaymentDetail.Data.ToList())
{
//i want add
//req._payment._cash.details.runningno = res.runningno //Ex. 10
//req._payment._cash.details.amount = res.amount //Ex. 99.9
//next loop
//req._payment._cash.details.runningno = res.runningno //Ex. 20
//req._payment._cash.details.amount = res.amount //Ex. 23.2
}
//sent to other api
response = await client.PostAsJsonAsync("", req._payment._cash);
.....
.....
}
i want result code when add list data to req._payment._cash:
(because to use it next process)
"createby": "system",
"createdate": 26/09/2018",
"details": [
{
"runningno": "10", //before add data to list is null
"amount": 99.9 //before add data to list is null
},
{
"runningno": "20", //before add data to list is null
"amount": 23.2 //before add data to list is null
}
]
Help me please. Thanks in advance.
List<ExCashtransactionDetailsRequest> detailsObj = new List<ExCashtransactionDetailsRequest>();
foreach (var res in resPaymentDetail.Data.ToList())
{
detailsObj.Add(new ExCashtransactionDetailsRequest(){ runningno =res.runningno, amount = res.amount });
}
and finally, add details object to your property
req._payment._cash.details = detailsObj;

How to map nested Property with Automapper

I am trying to map Student with StudentDto, this is what I am doing but it is complaining about the nested property which is of type List<StudentContact>
Both the objects, StudentDto and Student have exactly the same properties, this is what i am using to try to map the objects.
var config = new MapperConfiguration(
cfg => cfg.CreateMap<StudentDto, Student>());
var mapper = config.CreateMapper();
var driverActivationResponse = mapper.Map <List<Student> > (studentDto);// "studentDto" is List<StudentDto>
my classes
public class StudentDto
{
public StudentDto()
{
if(StudentContacts==null) StudentContacts=new List<StudentContact>();
}
public string Id { get; set; }
public List<StudentContact> StudentContacts { get; set; }
}
public class Student
{
public Student()
{
if(StudentContacts==null) StudentContacts=new List<StudentContact>();
}
public string Id { get; set; }
public List<StudentContact> StudentContacts { get; set; }
}
public class StudentContact
{
public string ContactName { get; set; }
public string PrimaryContactNo { get; set; }
}
This should help -
AutoMapper.Mapper.CreateMap<Student, StudentDto>()
.ForMember(a => a.StudentContacts, b => b.ResolveUsing(c => c.StudentContacts));
var map = Mapper.Map<StudentDto>(new Student
{
Id = "100",
StudentContacts = new List<StudentContact>
{
new StudentContact{ContactName = "test",PrimaryContactNo = "tset"}
}
});
you cannot map like mapper.Map <List<Student>>(studentDto);. The top level member cannot be a list when using automapper.
Does it help to specify the source collection type and destination collection type in your Map call?
var driverActivationResponse = mapper.Map<List<Student>, List<StudentDto>>(studentDto);
It looks like the AutoMapper code you have is correct. If you're still getting an error, something else must be wrong. Perhaps your studentDto is not really a List<StudentDto>?
In any case, here's an entire example that works without error:
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
namespace ConsoleSandbox
{
class Program
{
public static void Main()
{
var config = new MapperConfiguration(
cfg => cfg.CreateMap<StudentDto, Student>());
var mapper = config.CreateMapper();
var studentDtos = new[]
{
new StudentDto
{
Id = "1",
StudentContacts = new[]
{
new StudentContact { ContactName = "Dan", PrimaryContactNo = "123" },
new StudentContact { ContactName = "Stan", PrimaryContactNo = "456" },
}.ToList()
},
new StudentDto
{
Id = "2",
StudentContacts = new[]
{
new StudentContact { ContactName = "Foo", PrimaryContactNo = "789" },
new StudentContact { ContactName = "Bar", PrimaryContactNo = "101112" },
}.ToList()
},
}.ToList();
var driverActivationResponse = mapper.Map<List<Student>>(studentDtos);
Console.WriteLine($"Contacts Count: {driverActivationResponse.Count}");
Console.ReadKey();
}
}
public class StudentDto
{
public string Id { get; set; }
public List<StudentContact> StudentContacts { get; set; }
public StudentDto()
{
if (StudentContacts == null) StudentContacts = new List<StudentContact>();
}
}
public class Student
{
public string Id { get; set; }
public List<StudentContact> StudentContacts { get; set; }
public Student()
{
if (StudentContacts == null) StudentContacts = new List<StudentContact>();
}
}
public class StudentContact
{
public string ContactName { get; set; }
public string PrimaryContactNo { get; set; }
}
}

Cannot implicitly convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.ICollection<System.Web.Mvc.SelectList>'

I am trying to add some values into my SelectList data member in my object but I get an error
public ActionResult Create()
{
var paf = new ProductAddForm();
paf.Sizes = new SelectList(m.GetProductSizes());
paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");
return View(paf);
}
that is my creat function, and the paf.Sizes / paf.Suppliers code does not work.
My productaddform class:
public class ProductAddForm
{
public double MSRP { get; set; }
public string Name { get; set; }
public string ProductId { get; set; }
public ICollection<SelectList> Sizes { get; set; }
public ICollection<SelectList> Suppliers { get; set; }
public string UPC { get; set; }
}
And my methods in my manager.cs
public IEnumerable<SupplierList> GetAllSuppliersList()
{
var fetchedObjects = ds.Suppliers.OrderBy(n => n.Name);
var Suppliers = new List<SupplierList>();
foreach (var item in fetchedObjects)
{
var s = new SupplierList();
s.Name = item.Name;
s.Id = item.Id;
Suppliers.Add(s);
}
return (Suppliers);
}
public List<string> GetProductSizes()
{
return new List<string>() { "Small", "Medium", "Large" };
}
Whats wrong?
Suppliers is a collection of SelectList. So you need to Add item into the collection
Change
paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");
to
paf.Suppliers.Add(new SelectList(m.GetAllSuppliersList(), "Id", "Name"));

Categories

Resources