2018年5月30日 星期三

四捨五入且去除結尾的0及.

var a=2.335;
a.toMaxFixed(2) => "2.34"
a=2
a.toMaxFixed(2) => "2"
a=2.3
a.toMaxFixed(2) => "2.3"

Number.prototype.toMaxFixed = function (最大小數位) {
    return this.toFixed(最大小數位).replace(/0+$/, '').replace(/\.$/, '');
}

2018年5月8日 星期二

改善 SaveChanges() exception 顯示的錯誤訊息

擴充 .Context.cs 覆寫 SaveChanges() 顯示詳細的驗證錯誤訊息

1. 在Models資料夾底下新增資料夾,建議取名Extend
2. 新增class,檔名取相同名稱方便識別,如 Model1.Context.cs
3. 檔案範例內容如下
namespace xxx.Models
{
public partial class xxxEntities
    {
        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, "驗證錯誤訊息: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
        }
    }
}

參考來源

Entity Framework 建立新物件並儲存後馬上取得關聯資料

使用 CreateProxy 建立物件,不要直接 new var newmodel = _contextXXX.CreateProxy<yyy>(); ... _contextXXX.yyy.Add(newmodel); await _contextXXX.SaveC...