如何删除从 EF Code First 中的另一个实体引用的实体?
晚安。我有以下关系问题。 我有一个图片类Imagem
,
public class Imagem : Entity
{
public long Id {get ; set;}
public string Name{ get; set; }
}
我正在构建一种画廊,在画廊
的首页上有一张图像。
public class gallery: Entity
{
public long Id {get ; set;}
public Imagem Frontsheet{ get; set; }
}
我最大的问题是当我删除图像时它不会留下,因为 该图像与画廊相关联。
您如何处理这种情况,以便从图像表中删除图像?
Good night. I have the following relationship problem.
I have a picture class Imagem
public class Imagem : Entity
{
public long Id {get ; set;}
public string Name{ get; set; }
}
I'm building a kind of a gallery where I have an image on the front sheet of the gallery
.
public class gallery: Entity
{
public long Id {get ; set;}
public Imagem Frontsheet{ get; set; }
}
My biggest problem is when I delete an image it does not leave because
the image is associated with the gallery.
How do you treat this type of situation, in order to delete the image from the image table ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
数据库中有一个约束,如果任何图库通过
FrontSheet
属性引用该图像,则禁止删除该图像。您需要做的是将这些关系设置为NULL
。 (该关系似乎是可选的,因此您可以将数据库中的外键设置为NULL
。)对于您的模型,您必须选择引用您只想删除的图像的所有画廊。如果您想删除 Id =givenImageId
的图像,它看起来会像这样:如果您的
Gallery
实体上有一个外键属性......您不需要将首页与图库一起加载,这将提高性能:
You have a constraint in the database which forbids to delete an image if any gallery refers to it via the
FrontSheet
property. What you need to do is set these relationships toNULL
. (The relationship seems to be optional, so you can set the foreign key in the database toNULL
.) With your model you will have to select all galleries which refer to the image you just want to delete. It would look like this if you want to delete an image with Id =givenImageId
:If you would have a foreign key property on your
Gallery
entity......you would not need to load the frontsheets together with the galleries which would improve the performance:
我不确定实体之间的关系到底是什么,但看起来是 1:1 的关系。您需要配置关系以级联删除:
在上下文中实体的配置中执行此操作:
这是假设可选/必需关系。你也可以做一个必需的/必需的。它还假设您没有从图像到图库的导航属性。
如果您发布两个模型的完整代码,那么帮助您会容易得多。
如果您不希望数据库级联删除,您可以在删除图库之前删除图像。
I'm not sure exactly what your relationship is between the entities, but it looks like it is a 1:1 relationship. You need to configure the relationship to cascade the delete:
Do this in the configuration for your entities in your context:
This is assuming an optional / required relationship. You could also do a required/required. It also assumes that you don't have a navigation property from the Image to the gallery.
If you post the complete code for your two models it will be a lot easier to help you.
If you don't want the database to cascade the deletes you could just delete the Image before you delete the gallery.