多对多关系中的问题 [英] Problem in Many to Many Relationship

查看:121
本文介绍了多对多关系中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好
我有两个实体(资产和所有者).它们之间的关系是多对多的.

Hi anybody
I have two Entities(Asset and Owners). the relationship between them is many to many.

public class Asset
   {
       [Key]
       public int AssetId { get; set; }
       public string AssetName { get; set; }

       public List<Owners> Owners { get; set; }
   }







public class Owners
   {
       [Key]
       public int OwnerId { get; set; }
       public string Name { get; set; }

       public List<Asset> Assets { get; set; }
   }



好吧

我插入了三个资产,分别是计算机",表格"和平板电脑".

现在,我想插入一个新的所有者,并分配一些已经插入其中的资产.
我不想插入新资产,但我也只想为插入的所有所有者选择一些资产.但我不明白.


使用(var context = new MyContext())
{
所有者newOwner =新所有者{名称=布拉德"};
newOwner.Assets =//必须在这里分配一些已经插入的资产.
context.SaveChanges();
}

感谢



Ok

I insert three assets that is "Computer", "Table" and "Tablet".

Now, I want insert a new Owner and assign some of the asset that already inserted to it.
I don''t want insert a new asset, but also I want only select some asset for any owners that inserted. but I don''t understand do it.


using (var context = new MyContext())
{
Owners newOwner = new Owners { Name = "Brad" };
newOwner.Assets = // here must be assign some of assets that already inserted.
context.SaveChanges();
}

thanks

推荐答案

Owners newOwner = new Owners { Name = "Brad" };
Asset newAsset = new Asset{ AssetName= "Blah"};

newOwner.Assets.Add( newAsset);
context.SaveChanges();


这篇关于多对多关系中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆