我使用EntityFramework 6在我的c#model-first项目使用MySQL数据库一切正常,我可以毫无问题地生成我的数据库。
然后我修改了我的.edmx- 首先设计器没有更新CSDL内容和C-S映射内容.edmx文件的部分。所以我自己更新了内容,最终可以编译项目了。
这是.edmx文件现在的样子和在设计器中的样子:
EDMX文件:http://pastebin.com/Xer9UyNR
下面是设计器视图的链接:https://i.stack.imgur.com/Vcv9W.png
- 第二(也是最重要的一个),当EF试图从我的数据库中获得一个tinyint并将其类型更改为布尔值时,我得到一个FormatException。
这是我的GetCupboardByGuid方法:
public Cupboard GetCupboardByGuid(String guid)
{
using (var context = new ArmoireOutilsEntities())
{
var cupboard = (from a in context.Cupboards
where a.GUID.Equals(guid)
select a)
.Include("ResidentTools")
.Include("Tools")
.Include("Users") //If I remove this, .SingleOrDefault() works fine.
.SingleOrDefault(); //Throw FormatException when getting the User.Active value from the database.
if (cupboard != null)
cupboard.RefreshLists();
return cupboard;
}
}
这是我的User类生成的。edmx tt:
public partial class User
{
public User()
{
this.Tools = new ObservableCollection<Tool>();
this.Cupboards = new ObservableCollection<Cupboard>();
this.Active = true;
}
public int Id { get; set; }
public short Type { get; set; }
public string Firstname { get; set; }
public string LastName { get; set; }
public string Login { get; set; }
public short Gender { get; set; }
public short LangId { get; set; }
public string Photo { get; set; }
public System.DateTime CreationDate { get; set; }
public Nullable<System.DateTime> ModificationDate { get; set; }
public Nullable<System.DateTime> LastConnection { get; set; }
public Nullable<System.DateTime> DisableDate { get; set; }
public bool Active { get; set; }
public virtual Lang Lang { get; set; }
public virtual IList<Tool> Tools { get; set; }
public virtual IList<Cupboard> Cupboards { get; set; }
}
我猜EF遍历DB中cupboarduser中的所有用户(表连接用户到橱柜对于多对多关系),当涉及到设置Active时对于第一个用户,它从DB获得1,并将其作为字符串首先,然后尝试使用System.Boolean.Parse将该字符串解析为布尔值但是该方法不支持像"1"这样的数字为true(数据库中的字段是tinyint(1))。) .
那么为什么EF不能理解它是一个tinyint,所以他不能在System.Boolean.Parse中使用它?
?我试图重新生成整个.edmx=>
我试图重新生成整个.edmx文件从零开始=>相同的异常
我不明白为什么,因为我没有修改User模型,所以ActiveField已经在那里了,而且工作得很好。
很抱歉这么长时间,提前感谢。
最诚挚的问候,theCivilian
在特定实体上配置数据类型:
modelBuilder.Entity<User>()
.Property(p => p.Active)
.HasColumnType("bit");
或一般:
modelBuilder.Properties()
.Where(x => x.PropertyType == typeof(bool))
.Configure(x => x.HasColumnType("bit"));
这也可以使用实体中的Column
数据属性来实现。
[Column("Active", TypeName = "bit")]
[DefaultValue(false)]
public bool Active { get; set; }
我实际上不得不在连接字符串中设置TreatTinyAsBoolean=false,我的问题得到解决。
如果您先做这个DB,只需将TINYINT(1)类型更改为BIT(1),假设您确实需要一个布尔值。您可能还必须更新默认值(到位语法,例如b'0')。EF仍然会在你的实体中将这些转换为布尔值。