1.Get current date
 DateTime today = DateTime.Today;
var today = DateTime.Now;
var tomorrow = today.AddDays(1);
var yesterday = today.AddDays(-1);

2.datetimeto string

@item.WorkDate.Value.ToString("yyyy-MM-dd")

3.timespan to string

timespan.ToString("hh':'mm':'ss");
or
timespan.ToString(@"hh\:mm");

4.Entity Framework: adding existing child POCO to new Parent POCO, creates new child in DB

https://stackoverflow.com/questions/14307838/entity-framework-adding-existing-child-poco-to-new-parent-poco-creates-new-chi

Approach 1 - Setting Entity State

using (var context = new Context())
{
    var book = new Book();
    book.Name = "Service Design Patterns";
    book.Publisher = new Publisher() {Id = 2 }; // Only ID is required
    context.Entry(book.Publisher).State = EntityState.Unchanged;
    context.Books.Add(book);
    context.SaveChanges();
}

Approach 2 - Using Attach method

using (var context = new Context())
{
    var book = new Book();
    book.Name = "Service Design Patterns";                
    book.Publisher = new Publisher() { Id = 2 }; // Only ID is required
    context.Publishers.Attach(book.Publisher);
    context.Books.Add(book);
    context.SaveChanges();
}

 

    全站熱搜

    smartfly 發表在 痞客邦 留言(0) 人氣()