您的位置:首页 > 数据库

code first 使用已有的数据库并且改为Dbfirst获取Models的方法和TT模版

2015-09-19 00:01 429 查看
在开发中,我遇到了,已有数据库并且不需要从代杩改变或生成新的数据库表,但是这个问题 一直存在。

只要我向数据库插入数据,就会在原有的表基础上新增加一个带S 的数据表,如DataBase表,它会重新生成一个DataBases表。

查了好多API才找到解决办法,手工解决,在表少的时候还可以,要是表多了,以后要手功解决,会把人累死。

1.手动方法

首先在EF 4.1以后的版本里在这里写入一条:



让EF不再生成数据库表(也不再生成 __MigrationHistory)

然后手动在第个生成的实体类上添加:这样强制映射到数据库

[Table("Area")]

如图,



2.自动生成,则需要修改tt模板,修改XXXEntity.tt而不是XXXEntity.Context.tt

A.修改两个地方,这是里添加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)
: "";
}
B.添加Table的映射特性

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,现在就能愉快的编码了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: