简体   繁体   English

ASP.NET MVC如何访问Entity Framework生成的外键?

[英]ASP.NET MVC How to access Entity Framework generated foreign key?

Song has a many to many relationship with it's self. Song与自己有很多关系。 I store these ids in a class called SimilarVersion with both id columns. 我将这些id存储在一个名为SimilarVersion的类中, SimilarVersion包含两个id列。

public class Song
{
    public int Id { get; set; }

    public string AudioName { get; set; }

    public string ArtistName { get; set; }

    ...

    public virtual ICollection<SimilarVersion> SimilarVersions { get; set; } = new List<SimilarVersion>();      
}

public class SimilarVersion
{
    public int Id { get; set; }

    public int? Song_Id1 { get; set; }
}

View Models: 查看型号:

public class SongDto 
{
    public int Id { get; set; }

    public string AudioName { get; set; }

    public string ArtistName { get; set; }

    ...

    public ICollection<SimilarSongDto> SimilarSongDtos { get; set; } = new List<SimilarSongDto>();
}

public class SimilarSongDto
{
    public int Id { get; set; }

    public string AudioName { get; set; }

    public string ArtistName { get; set; }

    ...
}

The SimilarVersion table in my database now has Id , Song_Id , Song_Id1 , as EF has generated Song_Id. 我的数据库中的SimilarVersion表现在有IdSong_IdSong_Id1 ,因为EF生成了Song_Id。 How do I get to use that EF generated column in my code though? 我如何在我的代码中使用EF生成的列?

_similarVersionService.GetSimiliarVersion().Song_Id will give me an error because there is no property in the class called that. _similarVersionService.GetSimiliarVersion().Song_Id会给我一个错误,因为类中没有属性称为。 I could manually add it to the class like I have done with Song_Id1 and remove the collection from the other class but I think I must be doing something wrong. 我可以手动将它添加到类中,就像我使用Song_Id1并从其他类中删除该集合,但我认为我一定做错了。 Also please tell me if there is a better way of mapping this. 另外请告诉我是否有更好的映射方法。

I tried adding public int Song_Id { get; set; } 我尝试添加public int Song_Id { get; set; } public int Song_Id { get; set; } public int Song_Id { get; set; } and it just made another column in my table called Song_Id2 . public int Song_Id { get; set; } ,它只是改变了我的表的另一列称为Song_Id2

public ActionResult Song(int id)
{
    //Map the domainModel to songViewModel
    var songDto = Mapper.Map<Song, SongDto>(_songService.GetSong(id));

    //Get all of the songs where the id == the Song_Id column in similar version table
    var songs = _songService.GetSongs().ToList()
                .Where(x => x.SimilarVersions.Any(z => z.Song_Id == songDto.Id))
                .ToList(); //z.Song_Id no definition found

    //Map the Song domain to SimilarSong ViewModel and assign it to the songDto to be passed to the view
    songDto.SimilarSongDtos = Mapper.Map<ICollection<Song>, ICollection<SimilarSongDto>>(songs);

    return View(songDto);
}

Edit. 编辑。 Trying to add to a row based on Admir answer: 尝试根据Admir答案添加到一行:

var songToUpload = new Song
{
    AudioName = uploadSongDtos[i].AudioName.Trim(),
    ArtistName = uploadSongDtos[i].ArtistName,                        
};

 foreach (var compareAgainstString in _songService.GetSongs().ToDictionary(x => x.Id, x => x.AudioName))
 {
       var score = SearchContext.Levenshtein.iLD(songToUpload.AudioName, compareAgainstString.Value);

       //Don't add the current song
       if (score < 50 && songToUpload.Id != compareAgainstString.Key)
           songToUpload.SimilarVersionsWhereSimilar.Add(new SimilarVersion { SimilarId = compareAgainstString.Key });
 }

Both OriginalId and SimilarId are assigned to whatever the id of songToUpload.Id is given the relationship we defined in models, which is correct for OriginalId but it is also overriding my custom set SimilarId above. 无论OriginalIdSimilarId被分配到任何的ID songToUpload.Id给予我们在模型中定义的关系,这是正确的OriginalId但它也覆盖我的自定义设置SimilarId以上。 How can I stop this? 我怎么能阻止这个?

It is likely the ID is actually generated by your Store. ID很可能是由您的商店实际生成的。 Call Context.SaveChanges() to create it, then read the ID. 调用Context.SaveChanges()来创建它, 然后读取ID。

You can take this approach: 你可以采取这种方法:

public class Song
{
    public int Id { get; set; }

    public string ArtistName { get; set; }

    public virtual IList<Similarity> SimilaritiesWhereOriginal { get; set; }

    public virtual IList<Similarity> SimilaritiesWhereSimilar { get; set; } 
}

public class Similarity
{
    public int Id { get; set; }

    public int OriginalId { get; set; }
    public virtual Song Original { get; set; }

    public int SimilarId { get; set; }
    public virtual Song Similar { get; set; }
}

public class ApplicationDbContext : DbContext
{
    public DbSet<Song> Songs { get; set; }

    public DbSet<Similarity> Similarities { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Song>().HasMany(x => x.SimilaritiesWhereOriginal).WithRequired(x => x.Original).WillCascadeOnDelete(false);
        modelBuilder.Entity<Song>().HasMany(x => x.SimilaritiesWhereSimilar).WithRequired(x => x.Similar).WillCascadeOnDelete(false);
        base.OnModelCreating(modelBuilder);
    }
}

Similarity class shows relationship between "original" song and "similar" song. 相似度表示“原始”歌曲和“相似”歌曲之间的关系。 This class replaces EF auto-generated table with your own many-2-many relationship table that you can access from the code. 此类将EF自动生成的表替换为您可以从代码中访问的自己的多对多关系表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 没有实体框架外键关系的ASP.NET MVC - Asp.net mvc without entity framework foreign key relationships 如何在 Entity Framework Core 和 ASP.NET Core MVC 中使用外键 - How work with foreign key in Entity Framework Core & ASP.NET Core MVC 如何在ASP.NET MVC中使用实体框架在父表中创建外键并将其分配给子表 - How to create the foreign key in the parent table and assign it to the child table using entity framework in asp.net mvc 如何使用ASP.NET MVC中的Entity Framework将记录插入到具有外键的表中 - How to insert a record into a table with a foreign key using Entity Framework in ASP.NET MVC 我如何在Asp.Net MVC中使用Entity Framework和Web Api获取外键表数据 - How do i get foreign key table data using Entity Framework and Web Api in Asp.Net MVC 使用实体框架的代码优先方法在ASP.NET MVC应用程序中缺少外键关系 - Foreign key relationship missing in ASP.NET MVC app using code-first approach with Entity Framework 首先在ASP.net MVC实体框架代码中创建外键关系 - Create Foreign Key Relationship in ASP.net MVC Entity Framework Code First ASP.NET MVC和实体框架:生成的数据验证 - ASP.NET MVC and Entity Framework: Generated Data Validation 如何使用 LINQ 表达式 ASP.NET MVC Entity Framework 使用外键更新多个表 - How to Update multiple tables with foreign keys using LINQ expression ASP.NET MVC Entity Framework ASP.NET C#实体框架-如何正确更新外键? - ASP.NET C# Entity Framework - How to update Foreign Key properly?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM