English 中文(简体)
Linq, lambda expression
原标题:Linq, lambda expression

我有一个拥有“许多”关系的数据库。 我与Mlambda和linq一起试图把一个进入许多到许多桌子。

I have one Ado-entity called Book and another called Author. Book contains the navigation property Authors and Author contains the property Books.

现在,我想从我的行文中删除一本书。 为了做到这一点,我不得不在<代码>AuthorBooks-table>上删除其外在钥匙,但事实证明这很困难。

这是当时我的辛勤:

var a = db.db.Authors.Select(c => db.db.Authors.Where(c.Books.Contains(book));

This is not accepted by Visual studio and I don t know how to get to where I want. Thanks in advance!

我错误的照片:


http://olofd.dyndns.org:8887/pic1.PNG


http://olofd.dyndns.org:8887/pic2.PNG


http://olofd.dyndns.org:8887/pic3.PNG

最佳回答

下面的法典应当予以确定:

book = db.Books.Single(b => b.BookId == book.BookId);
 var bookCopies = db.BookCopies.Where(c => c.BookId == book.BookId).ToList();

 foreach (BookCopy c in bookCopies)
 {
     db.BookCopies.DeleteObject(c);
 }

 var authors = db.Authors.Include("Books").Where(author => author.Books.Any(b => b.BookId == book.BookId)).ToList();

 foreach (Author a in authors)
 {
     a.Books.Remove(book);
 }

 db.DeleteObject(book);
 db.SaveChanges();

The reason you got the error was because you didn t include the Books relationship when loading the authors. Because of this you looped trough an author collection where each author had zero books. Removing the book with a.Books.Remove(book) didn t do anything.

你可以看到,当你检查 d时就发生了这种情况。 反对: 删除实体但在国家管理人员中没有任何表现的地方。

您还需要在询问中增加一名前言。 否则,你将把实体从与你一样的收集中删除,这将成为一个例外。

问题回答

似乎你多次重新指出许多事情。 我期待看到这样的情况:

var authors = db.Authors.Where(author => author.Books.Contains(book));

为了诚实起见,我要hope:当你删除该实体时,LINQ会已经取消对你的外国关键关系——你们是否肯定了这一关系?





相关问题
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. ...

热门标签