本文介绍了甲骨文ODP.Net和EF CodeFirst - 的SaveChanges错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能帮助我这样的:

中的代码:

Role r = new Role { ID = 1, Name = "Members" };
ctx.Roles.Attach(r);

//Saving User
User u = new User {
    Login = login,
    Password = password,
    Status = 1
};
u.Roles.Add(r);

ctx.Users.Add(u);
ctx.SaveChanges();



我试图做的是保存一个新的用户与现有的角色。用户和角色类有许多一对多的关系,用一口流利的API映射如下:

What I'm trying to do is to save a new user with an existing role. User and Role classes have a many-to-many relationship mapped by fluent-api as follows:

modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(x => {
    x.ToTable("USER_ROLE_XREF", dbsch);
    x.MapLeftKey("ID_USER");
    x.MapRightKey("ID_ROLE");
});



但是,当调用SaveChanges我得到这个错误:
{指定的值类型不是Edm.Decimal'\r\\\
Parameter名的'一个实例:值}

But when the SaveChanges is called I get this error:{"The specified value is not an instance of type 'Edm.Decimal'\r\nParameter name: value"}

其实,我总是试图挽救一个单一的SaveChanges(相关实体)调用我得到同样的错误。所以,我必须做什么才能算出这个是使多个呼叫等行之有效的:

Actually, always I try to save related entities with a single SaveChanges() call I get the same error. so, what I had to do to figure this was to make multiple calls and so works well:

Role r = new Role { ID = 1, Name = "Members" };
ctx.Roles.Attach(r);

//Saving User
User u = new User {
    Login = login,
    Password = password,
    Status = 1
};

ctx.Users.Add(u);
ctx.SaveChanges();

//Assigning Member Role
u.Roles.Add(r);
ctx.SaveChanges();



这是我的理解是EF支持保存多个变化与单一的SaveChanges打电话,所以我想知道什么是错在这里。

It is my understanding that EF support to save multiple changes with a single SaveChanges call, so I'm wondering what's wrong here.

推荐答案

有这个想法的附加()方法是,你有被称为是在DB但这种情况下没有被跟踪的实体,对不对?我对你的问题是你肯定知道,这个角色在这里:

The idea with the Attach() method is that you have an entity that is known to be in the DB but not being tracked by this context, right? My question to you is do you know for sure that this Role here:

Role r = new Role { ID = 1, Name = "Members" };



东西已经存在?如果不是这样,我不认为你需要做的是用

is something that exists already? If it doesn't, I don't think what you want to do is use

ctx.Roles.Attach(r);



相反,它是你写的:

rather it is that you'd write:

ctx.Roles.Add(r);

和那么你可以回过头来写

and then you could turn around and write

User u = new User {
    Login = login,
    Password = password,
    Status = 1,
};

ctx.Users.Add(u);
u.Roles.Add(r);
ctx.SaveChanges();



你的第一个例子中有问题的是,这个新的角色确实是新来的数据库,以便安装它不是'T你想要做什么,而你想添加它。

The issue your first example has is that this new Role is really new to the DB so attaching it isn't what you'd want to do, rather you'd want to Add it.

和以单呼ctx.SaveChanges() 应该只是罚款这里。

And the single call to ctx.SaveChanges() should work just fine here.

这篇关于甲骨文ODP.Net和EF CodeFirst - 的SaveChanges错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 03:12