Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架6-保存相关实体_C#_.net_Entity Framework_Entity Framework 6 - Fatal编程技术网

C# 实体框架6-保存相关实体

C# 实体框架6-保存相关实体,c#,.net,entity-framework,entity-framework-6,C#,.net,Entity Framework,Entity Framework 6,我有以下实体: public class Artist { [Key] public string ArtistId { get; set; } public string Name { get; set; } public virtual ICollection<Genre> Genres { get; set; } } public class Genre { [Key] public int GenreId { get; se

我有以下实体:

public class Artist
{
    [Key]
    public string ArtistId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Genre> Genres { get; set; }
}

public class Genre
{
    [Key]
    public int GenreId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Artist> Artist { get; set; }
}
艺术家确实拥有
类型的属性。
不幸的是,当调用
context.SaveChanges()时,只有艺术家被保存到数据库中,而流派没有

我是否必须配置一些特殊的东西,以便相关实体(类型)也自动保存到数据库中

提前谢谢

编辑:
.ToArtist()
如下所示:

public static class ArtistExtensions
{
    public static Artist ToArtist(this FullArtistWrapper value)
    {
        if (value == null) { throw new ArgumentNullException(); }

        return new Artist
        {
            ArtistId = value.Id,
            Name = value.Name,
            Genres = new List<Genre>(value.Genres.Select(x => x.ToGenre()))
        };
    }
}
public static class GenreExtensions
{
    public static Genre ToGenre(this string value)
    {
        return new Genre
        {
            Name = value
        };
    }
}

我假设您正在使用延迟加载的代理类,因为您的导航属性设置为
virtual
。问题是您正在
ToArtist
中创建一个新的
列表
,它将覆盖代理的集合。尝试将项目添加到现有集合中


另一个问题可能是您没有使用代理。如果使用,代理将仅用于新实体。否则,您必须手动将所有相关实体添加到bContext`中。

如果我理解,如果您只想在艺术家保存到数据库时保存流派,请尝试填充流派的艺术家。比如说

List<Genres> lstGenres...

artist.Genres = lstGenres;

context.Entry(artist).State = EntityState.Added;
列出所有类型。。。
artist.Genres=lstyres;
context.Entry(artist.State=EntityState.Added;

希望对您有所帮助=)

您的ToArtist()代码是什么?你是在上下文中添加体裁吗?嘿@romanoza谢谢你的评论,我已经在问题中添加了代码:-)
List<Genres> lstGenres...

artist.Genres = lstGenres;

context.Entry(artist).State = EntityState.Added;