目前分類:ASP.NET (3)

瀏覽方式: 標題列表 簡短摘要
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) 人氣()

 

1.[IQueryable]order by two or more properties

OrderBy(i => i.PropertyName).ThenBy(i => i.AnotherProperty)

2.OrderBy list for only Date but not Time 

error:The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

rderBy(i => EntityFunctions.TruncateTime(i.CreateDate))

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

1.Concatenating strings

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

With C# 6

@($"{Model.address} {Model.city}")

 

2.date to string
(1)Published若為not nullable
@item.Published.ToString("yyyy-MM-dd")

(2)Published若為nullable

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

3.check string null/empty

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}

4.prevent escaping html in Razor

Html.Raw(Model.Content)

 

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