Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

left join between my EF entity class and my custom class function

$
0
0

i try to join my class which represent db table and another class static function which return series of date. my code is working but i am not getting desired value.

the class MyData has some missing date and my static function return dates. if the date static function return not found in MyData then i want to return zero value for EAmount field for that row. if data found in MyData for the date which return static function then i will return EAmount actual value.

[Table("MyData")]
public partial class MyData
{
    public int ID { get; set; }

    public DateTime? EDate { get; set; }

    public decimal? EAmount { get; set; }

    public DateTime? AddDate { get; set; }

    public DateTime? ModDate { get; set; }
}

my requirement something like i left join between two table.

suppose table 1 has date and table 2 has date and amount. join will be based on date. if there is no matching date in table2 for date present in table 1 then i want to show table 1 date and zero as value but if date match then i will take date from table 1 and amount from table 2. this is my simple requirement which i am trying to do by EF joining a EF entity table and a static function.

so here static function will play the role for table1 and EF entity class play role for table2.

here is my full code. code execute but the problem is EAmount value is getting always zero.


full code
----------

[Table("MyData")]
public partial class MyData
{
    public int ID { get; set; }

    public DateTime? EDate { get; set; }

    public decimal? EAmount { get; set; }

    public DateTime? AddDate { get; set; }

    public DateTime? ModDate { get; set; }
}

public class DateRange
{
    public static List<DateTime> GetDates(DateTime startdate, DateTime enddate)
    {
        List<DateTime> dates = Enumerable.Range(0, (enddate - startdate).Days + 1)
            .Select(day => startdate.AddDays(day)).ToList();

        return dates;
    }
}

public partial class LocalDbContext : DbContext
{
    public LocalDbContext()
        : base("name=LocalTest")
    {
    }

    public virtual DbSet<MyData> MyDatas { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    }
}

calling like this way

    using (var db = new LocalDbContext())
    {

        var result = from p in DateRange.GetDates(new DateTime(2017, 01, 01), new DateTime(2017, 01, 20))
                     join n in db.MyDatas on p equals n.EDate into g
                     from x in g.DefaultIfEmpty()
                     select new
                     {
                         date = p,
                         amount = x == null ? 0 : x.EAmount
                     };

        var xx = result.ToList();
    }

thanks



Viewing all articles
Browse latest Browse all 1698

Trending Articles