---
# System prepended metadata

title: EF Has no parameterless construct issue
tags: [DotNet, Entity Framework]

---

###### tags: `DotNet` `Entity Framework`

# EF Has no parameterless construct issue

## 情境

近期在某專案在Service Layer使用Persistence Layer EF6 Entity時，特定根據情境宣告需注入參數的建構子。情境如下

### Entity Model

```csharp=
/// <summary>
/// Cut channel mark (3D Channel排序)
/// </summary>
[Table(nameof(ProductInfo_CutChMark))]
public class ProductInfo_CutChMark : BaseEntityModel
{
	/// <summary>
	/// Serial Number Ex:60A0MN8G0006
	/// </summary>
	[Key, Column(Order = 1), MaxLength(20)]
	public string SN { get; set; }

	/// <summary>
	/// Product Type Ex:118X118
	/// </summary>
	[Column(Order = 2), MaxLength(20), Required]
	public string ProductType { get; set; }

	/// <summary>
	/// ALIGN: Align Stage
	/// PRE:將完成ALIGN的BAREBONE裝入HOUSING後的檢查
	/// 空值: Calibration
	/// FINAL:指完成CONNECTOR製作後的最後測試
	/// </summary>
	[Key, Column(Order = 3), MaxLength(20)]
	public string UsageStage { get; set; }

	/// <summary>
	/// 實體Channel編號 1,2,3,4,5
	/// </summary>
	[Column(Order = 4), MaxLength(500)]
	public string Physical_ChNo { get; set; }

	/// <summary>
	/// 邏輯In Channel編號 0,1,2.. (0表不用)
	/// </summary>
	[Column(Order = 5), MaxLength(500)]
	public string Logic_InChNo { get; set; }

	/// <summary>
	/// 邏輯Out Channel編號 0,1,2.. (0表不用)
	/// </summary>
	[Column(Order = 6), MaxLength(500)]
	public string Logic_OutChNo { get; set; }

	/// <summary>
	/// MEMS In Chip Status (Normal, Spare, Reserved, Cutoff) -1,2,-1,-1,2	0,1,2,0..
	/// </summary>
	[Column(Order = 7), MaxLength(500)]
	public string Status_InCh { get; set; }

	/// <summary>
	/// MEMS Out Chip Status (Normal, Spare, Reserved, Cutoff) -1,2,-1,-1,2	0,1,2,0..
	/// </summary>
	[Column(Order = 8), MaxLength(500)]
	public string Status_OutCh { get; set; }
    
        /// <summary>
        /// Construct
        /// </summary>
        /// <param name="sn">Serial Number Ex:60A0MN8G0006</param>
        /// <param name="productType">Product Type Ex:118X118</param>
	public ProductInfo_CutChMark(string sn, string productType)
	{
		SN = sn;
		ProductType = productType;      
	}
	
}
```

## 錯誤訊息

如情境所述，此時在使用ProductInfo_CutChMark EF Model時需注入SN與ProductType 兩個參數。結果在使用DBContext時跳出下述錯誤

> has no parameterless construct

![](https://i.imgur.com/hWSti6U.png)

## 解決方法

基本上Persistence Layer大部分狀況都是使用PO Model，理論上可以不用宣告可注入的建構子設定。稍微查一下專案中我使用此EF Model的實際狀況，確實有落實基本的三層設計，只是Service Layer使用Model下意識覺得SN跟ProductType為必須參數做了這個設定。故

把需注入的建構子拿掉就正常了，又或是可以宣告一個空的建構子。但設計上應該不會這樣做，故前者的方法還是比較好。從這錯誤大致也知道EF Framework在Persistence Layer某種程度會希望設計者能落實PO設計。所以我覺得較好的方式可以用Mapping方式去Mapping BO與PO(Net與Net Core則使用AutoMapper)。
