code first 使用已有的資料庫並且改為Dbfirst獲取Models的方法和TT模版
阿新 • • 發佈:2019-01-28
在開發中,我遇到了,已有資料庫並且不需要從代榪改變或生成新的資料庫表,但是這個問題 一直存在。
只要我向資料庫插入資料,就會在原有的表基礎上新增加一個帶S 的資料表,如DataBase表,它會重新生成一個DataBases表。
查了好多API才找到解決辦法,手工解決,在表少的時候還可以,要是表多了,以後要手功解決,會把人累死。
1.手動方法
首先在EF 4.1以後的版本里在這裡寫入一條:
讓EF不再生成資料庫表(也不再生成 __MigrationHistory)
然後手動在第個生成的實體類上新增:這樣強制對映到資料庫
[Table("Area")]
如圖,
2.自動生成,則需要修改tt模板,修改XXXEntity.tt而不是XXXEntity.Context.tt
A.修改兩個地方,這是裡新增Table的引用
B.新增Table的對映特性public string UsingDirectives(bool inHeader, bool includeCollections = true) { return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion()) ? string.Format( CultureInfo.InvariantCulture, "{0}using System;{1}" + "{2}" + "{3}", inHeader ? Environment.NewLine : "", includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "", includeCollections ? (Environment.NewLine + "using System.ComponentModel.DataAnnotations.Schema;") : "", inHeader ? "" : Environment.NewLine) : ""; }
public string EntityClassOpening(EntityType entity) { return string.Format( CultureInfo.InvariantCulture, "[Table(\""+"{4}"+"\")]"+"{5}"+"{0} {1}partial class {2}{3}", Accessibility.ForType(entity), _code.SpaceAfter(_code.AbstractOption(entity)), _code.Escape(entity), _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)), _code.Escape(entity), Environment.NewLine ); }
OK,現在就能愉快的編碼了