Domanda

I need to join 2 table using petapoco MVC4 my table cong shown below

[TableName("District")]
[PrimaryKey("nDistrictID")]
public class District
{   
    public int nDistrictID { get; set; }
    public string cDistrictName { get; set; }
    public bool bActive { get; set; }
    public int nStateID { get; set; }
}

And state table

[PetaPoco.TableName("States")]
[PetaPoco.PrimaryKey("nStateID")]
public class States
{
    public int nStateID { get; set; }
    public string cStateName { get; set; }      
}

I need a query in this form

select d.cDistrictName,s.cStateName, d.nStateID from District
       d inner join States s on d.nStateID=s.nStateID
È stato utile?

Soluzione

I am assuming you have already a dataContext which contains 2 DbSet of each classes. Regarding that you can use: Regarding the result you expect, you can create a new class which matches with the result:

public class DistrictWithState
{
  public string cDistrictName {get;set;}
  public string cStateName {get; set;}
  public int nStateId {get;set;}
} 

Then in your Action:

  var dataContext = new PetaPoco.Database("mysql"); 
  var sql="select d.cDistrictName,s.cStateName, d.nStateID from District
   d inner join States s on d.nStateID=s.nStateID";

  var districts = db.Fetch<DistrictWithState>(sql);

 return view(districts);

There is another solution using the dynamic keyword. But just start with that solution above. It should work. I hope it will help

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top