1 回答

TA貢獻1877條經驗 獲得超6個贊
和[Computed]
都會Write(false)
忽略屬性 whileINSERT
以及UPDATE
操作。所以,它們兩者是相同的。您可以使用其中任何一種。
文檔如下:
[Write(true/false)]
- 該屬性不可寫
[Computed]
- 該屬性是計算得出的,不應成為更新的一部分
關于Write
:
如上面文檔的第一行所述,Write
處理“可寫”行為。這應該包括INSERT
和UPDATE
。
var properties = type.GetProperties().Where(IsWriteable).ToArray();
...
...
...
private static bool IsWriteable(PropertyInfo pi)
{
? ? var attributes = pi.GetCustomAttributes(typeof(WriteAttribute), false).AsList();
? ? if (attributes.Count != 1) return true;
? ? var writeAttribute = (WriteAttribute)attributes[0];
? ? return writeAttribute.Write;
}
關于Computed
:
上面文檔中的第二行有點寬泛。
不應成為更新的一部分
這是否意味著它可以成為 的一部分INSERT
?不,不是的;?它還涵蓋了這兩個動作??梢酝ㄟ^以下代碼觀察到這一點:
CREATE TABLE TestTable
(
? ? [ID]? ? ? ? ? ? [INT] IDENTITY (1,1) NOT NULL CONSTRAINT TestTable_P_KEY PRIMARY KEY,
? ? [Name]? ? ? ? ? [VARCHAR] (100) NOT NULL,
? ? [ComputedCol]? ?[VARCHAR] (100) NOT NULL DEFAULT '',
? ? [NonWriteCol]? ?[VARCHAR] (100) NOT NULL DEFAULT ''
)
[Table("TestTable")]
public class MyTable
{
? ? [Key]
? ? public int ID { get; set; }
? ? public string Name { get; set; }
? ? [Computed]
? ? public string ComputedCol { get; set; }
? ? [Write(false)]
? ? public string NonWriteCol { get; set; }
}
int id;
using(SqlConnection conn = new SqlConnection(@"connection string"))
{
? ? MyTable myTable = new MyTable();
? ? myTable.Name = "Name";
? ? myTable.ComputedCol = "computed";
? ? myTable.NonWriteCol = "writable";
? ? conn.Insert<MyTable>(myTable);
? ? id = myTable.ID;
}
using(SqlConnection conn = new SqlConnection(@"connection string"))
{
? ? MyTable myTable = conn.Get<MyTable>(id);
? ? myTable.Name = "Name_1";
? ? myTable.ComputedCol = "computed_1";
? ? myTable.NonWriteCol = "writable_1";
? ? conn.Update<MyTable>(myTable);
}
通過上面的代碼,您將觀察到無論您選擇哪個屬性來裝飾屬性,它都不會被考慮 forINSERT
或 for?UPDATE
。所以基本上,這兩個屬性都扮演著相同的角色。
這可以在 github 上的Dapper.Tests.Contrib測試項目中得到進一步證實。
[Table("Automobiles")]
public class Car
{
? ? public int Id { get; set; }
? ? public string Name { get; set; }
? ? [Computed]
? ? public string Computed { get; set; }
}
...
...
...
//insert with computed attribute that should be ignored
connection.Insert(new Car { Name = "Volvo", Computed = "this property should be ignored" });
- 1 回答
- 0 關注
- 158 瀏覽
添加回答
舉報