I am new on Dapper.NET kinda stuck on this. I am trying to fill a class which has another class from multirow result set.
# DATABASE SP >
SELECT b.BuildingId, b.BuildingName, b.Wood, b.Food, b.Stone, b.Gold FROM UserBuildings ub, Buildings b WHERE b.BuildingId = ub.BuildingId AND UserId = #UserId
# CODE >
using (IDbConnection connection = OpenConnection())
{
List<Building.Building> buildings = new List<Building.Building>();
var multi = connection.QueryMultiple<Building.Building, Resource.Resource>("UserBuildingGet", new { UserId = UserId }, commandType: CommandType.StoredProcedure).ToList();
building.Resource = multi.Read<Resource.Resource>().Single();
return building;
}
# CLASSES >
public class Building
{
private int _BuildingId;
private string _BuildingName;
private Resource.Resource _Resource;
public int BuildingId
{
get { return _BuildingId; }
set { _BuildingId = value; }
}
public string BuildingName
{
get { return _BuildingName; }
set { _BuildingName = value; }
}
public Resource.Resource Resource
{
get { return _Resource; }
set { _Resource = value; }
}
public Building(int BuildingId, string BuildingName, Resource.Resource Resource)
{
this.BuildingId = BuildingId;
this.BuildingName = BuildingName;
this.Resource = Resource;
}
}
public class Resource
{
private int _Wood;
private int _Food;
private int _Stone;
private int _Gold;
public int Wood
{
get { return _Wood; }
set { _Wood = value; }
}
public int Food
{
get { return _Food; }
set { _Food = value; }
}
public int Stone
{
get { return _Stone; }
set { _Stone = value; }
}
public int Gold
{
get { return _Gold; }
set { _Gold = value; }
}
public Resource(int Wood, int Food, int Stone, int Gold)
{
this.Wood = Wood;
this.Food = Food;
this.Stone = Stone;
this.Gold = Gold;
}
}
Your code needs to define what separates the data. Use the splitOn parameter of GridReader.Read
var buildings = new List<Building.Building>();
using (IDbConnection connection = OpenConnection())
{
using(var reader = connection.QueryMultiple("UserBuildingGet",
new { UserId = UserId },
commandType: CommandType.StoredProcedure))
{
var building = reader.Read<Building.Building,
Resource.Resource,
Building.Building>
((b, r) => { b.Resource = r; return b; }, splitOn: "Wood");
buildings.AddRange(building);
}
}
return buildings;
See: Is there a way of using MultiMapping and QueryMultiple together in Dapper?
Sample:
public class Building
{
public int BuildingId { get; set; }
public string BuildingName { get; set; }
public Resource Resource { get; set; }
public override string ToString()
{
return string.Format("Id: {0} Name: {1} Resource: {2}", BuildingId, BuildingName, Resource);
}
}
public class Resource
{
public int Wood { get; set; }
public int Food { get; set; }
public int Stone { get; set; }
public int Gold { get; set; }
public override string ToString()
{
return string.Format("Wood: {0} Food: {1} Stone {2} Gold {3}", Wood, Food, Stone, Gold);
}
}
var sql = #"SELECT 1 AS BuildingId, 'tower' AS BuildingName, 1 AS Wood, 1 AS Food, 1 AS Stone, 1 AS Gold
UNION ALL
SELECT 2 AS BuildingId, 'shed' AS BuildingName, 1 AS Wood, 1 AS Food, 1 AS Stone, 1 AS Gold";
var buildings = new List<Building>();
using(var connection = GetOpenConnection())
{
using(var reader = connection.QueryMultiple(sql))
{
var building = reader.Read<Building, Resource, Building>(
(b, r) => { b.Resource = r; return b; }, splitOn: "Wood");
buildings.AddRange(building);
}
}
foreach(var building in buildings)
{
Console.WriteLine(building);
}
Related
How do I grab something like Name using the ID?
Code:
//PROPRIEDADES
public int Id
{
get { return id; }
set
{
if (value < 0)
throw new Exception("ID inválido");
id = value;
}
}
public string Username { get; set; }
public string Password { get; set; }
public string Nome_Completo { get; set; }
public string Email { get; set; }
...
CollectionBase:
public string idToName(int id)
{
foreach (Pessoa p in this.List)
{
if (p.Id == id)
{
return p.Nome_Completo;
}
}
return null;
}
Final result:
TABLE A: https://imgur.com/a/NuHG0sN NEED TO GET THE NOME_COMPLETO
TABLE B: https://imgur.com/a/xrf1GAU
Me trying to get the NAME FROM ID:
private void LoadListView()
{
lstvEncomendas.Items.Clear();
foreach (Encomenda en in brain.encomendas)
{
string[] subitems = new string[] { en.Id.ToString(), brain.pessoas.idToName(en.PessoaID)/*en.PessoaID.ToString()*/, en.Morada, en.Telefone, en.Descricao, en.Attachfile.ToString(), en.VoluntarioID.ToString(), en.Estado};
ListViewItem lviItem = new ListViewItem(subitems);
lstvEncomendas.Items.Add(lviItem);
}
}
I'm coding a func that inputs an array with different year of birth and prints out the oldest person.
I'm trying to add a validation with get and set but my syntax is wrong.
enter image description here
TL;DR
Properties declaration part:
public class Employee
{
private string _fullName;
private int _yearIn;
public string FullName
{
get => _fullName;
set
{
if (!string.IsNullOrEmpty(value))
{
_fullName = value;
}
}
}
public int YearIn
{
get => _yearIn;
set
{
if (value > 0 && value <= 2020)
{
_yearIn = YearIn;
}
}
}
}
And a usage:
var employees = new List<Employee>();
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Enter Name:");
string name = Console.ReadLine();
Console.WriteLine("Enter Year:");
int yearIn = Convert.ToInt32(Console.ReadLine());
employees.Add(new Employee
{
FullName = name,
YearIn = yearIn
});
}
Update
You can do the same in a bit different manner though:
public class Employee
{
private string _fullName;
private int _yearIn;
public bool IsNameValid { get; set; }
public bool IsYearValid { get; set; }
public string FullName
{
get => _fullName;
set
{
_fullName = value;
IsNameValid = string.IsNullOrEmpty(value);
}
}
public int YearIn
{
get => _yearIn;
set
{
_yearIn = value;
IsYearValid = (value < 0) || (value > 2020);
}
}
}
And later:
Console.WriteLine($"Employee name is: {employees[i].IsNameValid}");
Console.WriteLine($"Employee year is: {employees[i].IsYearValid}");
Update 2
And the last alternative version is that you can use Validation attributes:
public class Employee
{
[Required]
[Range(0, 2020)]
public int YearIn { get; set; }
[Required]
[StringLength(50)]
public string FullName { get; set; }
}
later:
var empl = new Employee{ YearIn = yearIn, FullName = name};
var context = new ValidationContext(empl, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(empl, context, results, true);
Console.WriteLine($"Is model valid: {isValid}");
if (isValid)
{
employees.Add(new Employee
{
FullName = name,
YearIn = yearIn
});
}
You can create wrapper classes over array and use indexer method for accessing the array item.
There in, you can put all your validation logic.
class IntData
{
public IntData(int size)
{
data = new int[size];
}
// Array of temperature values
private int[] data;
public int this[int index]
{
get
{
return data[index];
}
set
{
// Do your validation here
if (value < 5000)
{
data[index] = value;
}
}
}
}
static void Main(string[] args)
{
IntData year = new IntData(3);
year[0] = 2000;
year[1] = 6000; // This value won't set because of validation
year[2] = 4000;
Console.Read();
}
I have an error
Severity Code Description Project File Line Suppression State Error CS0161 'RateController.GetRateById(long)': not all code paths return a value shenoywebapi D:\shenoystudio\shenoywebapi\Controllers\RateController.cs 192 Active
[Route("api/rate/getrate/{id}")]
public Rate GetRateById(long id)
{
var result = new Rate();
var dsRate = SqlHelper.ExecuteDataset(AppDatabaseConnection, CommandType.StoredProcedure, 0, "GetRateById", new SqlParameter("#Id", id));
if (dsRate.Tables[0].Rows.Count > 0)
{
DataRow row = dsRate.Tables[0].Rows[0];
result = new Rate
{
Id = Convert.ToInt64(row[0]),
wefDate = Convert.ToDateTime(row[1]),
//ProductRates =new List<ProductRate>() { new ProductRate() { Rate = Convert.ToInt64(row[2])} }
};
}
var ProductRatesList = new List<ProductRate>();
var dsRateDetails = SqlHelper.ExecuteDataset(AppDatabaseConnection, CommandType.StoredProcedure, 0, "GetRateDetailsById", new SqlParameter("#RateId", id));
if (dsRateDetails.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dsRateDetails.Tables[0].Rows)
{
ProductRatesList.Add(new ProductRate
{
Rate = Convert.ToDecimal(row[0])
});
}
result.ProductRates = ProductRatesList;
return result;
}
}
This is my rate model
{
public class Rate
{
public long Id { get; set; }
public DateTime wefDate { get; set; }
public IList<ProductRate> ProductRates { get; set; }
}
}
This is my ProductRate Model
namespace shenoywebapi.Models
{
public class ProductRate
{
public long Id { get; set; }
public string SerialNumber { get; set; }
public long ProductId { get; set; }
public string ProductName { get; set; }
public string Unit { get; set; }
public decimal Rate { get; set; }
}
}
Only on this part you have a return statement:
if (dsRateDetails.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dsRateDetails.Tables[0].Rows)
{
ProductRatesList.Add(new ProductRate
{
Rate = Convert.ToDecimal(row[0])
});
}
result.ProductRates = ProductRatesList;
return result;
}
if the code goes not to this if statement, there is no return statement
if (dsRateDetails.Tables[0].Rows.Count > 0)
you should add this before the last curly brace of the method:
return result;
I think I'm getting stupid because I can't get my LINQ query to work as I expect. I have one class that has 3 relationships to other classes.
This is the main class
[Table(Name = "scanResult")]
public class SniffResult
{
public SniffResult()
{
}
public SniffResult(Address address)
{
this.address = address;
}
private int _pk_SniffResult;
[Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_SniffResult", Name ="pk_scanResult")]
public int pk_SniffResult { get { return _pk_SniffResult; } set { this._pk_SniffResult = value; } }
private int _fk_scan;
[Column(Storage = "_fk_scan", Name = "scan")]
public int fk_scan { get { return _fk_scan; } set { this._fk_scan = value; } }
private Scan _scan;
[Association(Storage = "_scan", IsForeignKey = true, ThisKey = "fk_scan", OtherKey = "pk_scan")]
public Scan scan { get { return _scan; } set { this._scan = value; } }
private int _fk_address;
[Column(Storage = "_fk_address", Name = "address")]
public int fk_adress { get { return _fk_address; } set { this._fk_address = value; } }
private Address _address;
[Association(Storage ="_address", IsForeignKey = true, ThisKey = "fk_adress", OtherKey = "pk_address")]
public Address address { get { return _address; } set { this._address = value; } }
private string _rawResult;
[Column(Storage = "_rawResult", Name = "raw")]
public string rawResult { get { return _rawResult; } set { this._rawResult = value; } }
private int _code = -5;
[Column(Storage = "_code")]
public int code { get { return _code; } set { this._code = value; } }
private DateTime _scanDate = DateTime.Now;
[Column(Storage = "_scanDate")]
public DateTime scanDate { get { return _scanDate; } set { this._scanDate = value; } }
private int? _fk_proxy;
[Column(Storage = "_fk_proxy", Name = "usedProxy", CanBeNull = true)]
public int? fk_proxy { get { return _fk_proxy; } set { this._fk_proxy = value; } }
private ProxyData _usedProxy;
[Association(Storage = "_usedProxy", IsForeignKey = true, ThisKey = "fk_proxy", OtherKey = "pk_proxy")]
public ProxyData usedProxy { get { return _usedProxy; } set { this._usedProxy = value; } }
public string message { get; set; } = "";
public bool availability { get; set; }
public int planCode { get; set; }
public string planning { get; set; }
public override string ToString()
{
return string.Format("availability={0}, code={1}, message={2}", availability, code, message);
}
}
This is one of the child classes
[Table(Name = "address")]
public class Address
{
private int _pk_address;
[Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_address")]
public int pk_address { get { return _pk_address; } set { this._pk_address = value; } }
private string _provId;
[Column(Storage = "_provId")]
public string provId { get { return _provId; } set { this._provId = value; } }
private string _zipcode;
[Column(Storage = "_zipcode")]
public string zipcode { get { return _zipcode; } set { this._zipcode = value; } }
private int _houseNumber;
[Column(Storage = "_houseNumber")]
public int houseNumber { get { return _houseNumber; } set { this._houseNumber = value; } }
private string _addressAddition;
[Column(Storage = "_addressAddition")]
public string addressAddition { get { return _addressAddition; } set { this._addressAddition = value; } }
public string ToAddresString()
{
return string.Format("{0} {1}{2}", this.provId, zipcode, houseNumber, addressAddition);
}
public override string ToString()
{
return string.Format("{0}:\t{1}\t{2}{3}", this.provId, zipcode, houseNumber, addressAddition);
}
}
I want to get SniffResult including the associated fields. But they are all null. This is the code I use:
SniffDAO dao = new SniffDAO();
var test = from sr in dao.SniffResults
where sr.fk_scan == 3
select sr;
foreach (var one in test)
{
Console.WriteLine(one.pk_SniffResult);
Console.WriteLine(one.address);
}
one.address gives me a null, what am I doing wrong?
This is the Dao class
public class SniffDAO
{
private string currentDir;
private DataContext db;
public Table<Scan> Scans { get; set; }
public Table<SniffResult> SniffResults { get; set; }
public Table<Address> Addresses { get; set; }
public SniffDAO()
{
db = new DataContext(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=********;Integrated Security=True;Asynchronous Processing=True");
db.ObjectTrackingEnabled = true;
Scans = db.GetTable<Scan>();
SniffResults = db.GetTable<SniffResult>();
Addresses = db.GetTable<Address>();
currentDir = Directory.GetCurrentDirectory();
}
public void save()
{
db.SubmitChanges();
}
}
You need to Include related entities like this:
SniffDAO dao = new SniffDAO();
var test = dao.SniffResults.Include(x=>x.address).Where(sr.fk_scan == 3);
foreach (var one in test)
{
Console.WriteLine(one.pk_SniffResult);
Console.WriteLine(one.address);
}
I found the solution thanks to #Kris. I now use:
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<SniffResult>(sr => sr.address);
dlo.LoadWith<SniffResult>(sr => sr.usedProxy);
dlo.LoadWith<SniffResult>(sr => sr.scan);
db.LoadOptions = dlo; //db is the DataContext
See https://msdn.microsoft.com/en-us/library/bb548760(v=vs.110).aspx for more info
I have this:
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
public List<???prpClass???> Whatever(string prpClass)
where string prpClass can be "Blah" or "Doh".
I would like the List type to be class Blah or Doh based on what the string prpClass holds.
How can I achieve this?
EDIT:
public List<prpClass??> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result;
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result;
}
return null
}
}
you have to have a common supertype:
public interface IHaveAnId
{
int id { get;set; }
}
public class Blah : IHaveAnId
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh : IHaveAnId
{
public int id {get;set;}
public string dohh { get; set; }
public string mahh { get; set; }
}
then you can do:
public List<IHaveAnId> TheList = new List<IHaveAnId>();
and in some method:
TheList.Add(new Blah{id=1,blahh = "someValue"});
TheList.Add(new Doh{id =2, dohh = "someValue", mahh = "someotherValue"});
to iterate through the list:
foreach(IHaveAnId item in TheList)
{
Console.WriteLine("TheList contains an item with id {0}", item.id);
//item.id is allowed since you access the property of the class over the interface
}
or to iterate through all Blahs:
foreach(Blah item in TheList.OfType<Blah>())
{
Console.WriteLine("TheList contains a Blah with id {0} and blahh ='{1}'", item.id, item.blahh);
}
Edit:
the 2 methods and a int field holding the autovalue:
private int autoValue = 0;
public void AddBlah(string blahh)
{
TheList.Add(new Blah{id = autovalue++, blahh = blahh});
}
public void AddDoh(string dohh, string mahh)
{
TheList.Add(new Doh{id = autovalue++, dohh = dohh, mahh = mahh});
}
Another Edit
public List<object> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result.Cast<object>().ToList();
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result.Cast<object>.ToList();
}
return null;
}
}
in the view you then have to decide what type it is. In asp.net MVC you can use a display template and use reflection to get a good design. But then i still don't know what technology you are using.
Yet another Edit
TestClass:
public class SomeClass
{
public string Property { get; set; }
}
Repository:
public static class Repository
{
public static List<object> Whatever(string prpClass)
{
switch (prpClass)
{
case "SomeClass":
return new List<SomeClass>()
{
new SomeClass{Property = "somestring"},
new SomeClass{Property = "someOtherString"}
}.Cast<object>().ToList();
default:
return null;
}
}
}
And a controller action in mvc:
public JsonResult Test(string className)
{
return Json(Repository.Whatever("SomeClass"),JsonRequestBehavior.AllowGet);
}
then i called it with: http://localhost:56619/Home/Test?className=SomeClass
And got the result:
[{"Property":"somestring"},{"Property":"someOtherString"}]
Is this what you are trying to do?
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
class Program
{
public static List<T> Whatever<T>(int count) where T: new()
{
return Enumerable.Range(0, count).Select((i) => new T()).ToList();
}
static void Main(string[] args)
{
var list=Whatever<Doh>(100);
// list containts 100 of "Doh"
}
}