English 中文(简体)
如何将字段与一个表格中的另一个字段连接起来?
原标题:How to connect the field with another field in one table?

我首先使用模型。

实体:

class User
{
Guid UserId{get;set;}
Guid RefererUserId {get;set;}
User RefereUser {get;set;}
}

数据引文 :

public class DataContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            modelBuilder.Entity<User>()
                .HasRequired(x => x.ReferrerUser)
                .WithMany()
                .HasForeignKey(x => x.ReferrerUserId).WillCascadeOnDelete(false);

        }
 public DbSet<User> Users { get; set; }
}

利用数据库:

MembershipCreateStatus Status;
Membership.CreateUser("Demo", "123456", "[email protected]", null, null, true, out Status);

Roles.CreateRole("Admin");
Roles.AddUserToRole("Demo", "Admin");
DataContext db = new DataContext();
var a = db.Users.Where(x => x.Email == "[email protected]").FirstOrDefault();
a.MoneyRUB = 100;
a.MoneyUSD = 100;
db.SaveChanges();

我得到错误 :

The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "User_ReferrerUser". The conflict occurred in database "Kamikaze", table "dbo.Users", column UserId . The statement has been terminated.

我做错什么了?

最佳回答

尝试使 ReferUserId 无效 (即 Guid? ,而不是 Guid )。 否则,将无法插入第一个用户 。

您还需要将 Has Required 改为 Hasoptional ,以使模型意识到可能不存在 ReferUser

“https://stackoverflow.com/a/8021125/335858><这一答复,以详细介绍在代码第一中建立可选链接的情况。

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签