【问题标题】:Code First domain classesCode First 域类
【发布时间】:2014-01-06 19:02:26
【问题描述】:

我是 ASP.Net MVC 和 EF Code First 的新手。我想创建一个专业的音乐分享网站。但我担心如果我在 Code First 中是正确的。我也想使用简单的会员资格或您建议的任何其他会员资格,并且我想在我的解决方案中使用分层。我应该有以下实体:

namespace MusicSite.Models
{
    public class Media
    {
        public int Id { get; set; }
        public MediaType MediaType { get; set; }
        public string  FilePath { get; set; }
        public string Title { get; set; }
    }
}

namespace MusicSite.Models
{
    public enum MediaType
    {
        MP3=1,
        MusicVideo=2,
        Photo=3
    }
}

namespace MusicSite.Models
{
    public class MP3:Media 
    {
        public Artist Artist { get; set; }
    }
}

namespace MusicSite.Models
{
    public class Artist
    {
        public User User { get; set; }
    }
}

namespace MusicSite.Models
{
    public class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

我不知道如何关联这些实体。你能帮忙吗?

【问题讨论】:

  • 也许你想先使用数据库?它使设置模型变得非常简单,然后您就不必担心设置关系了。
  • 有一个vs扩展,可以从exsit数据库生成类,也可以生成关系配置,你可以试试,看看生成了什么;这样你就可以学习如何配置关系visualstudiogallery.msdn.microsoft.com/…

标签: c# asp.net asp.net-mvc ef-code-first entity-framework-6


【解决方案1】:

首先关联模型中的实体,例如:

public class Media
{
    public Artist Artist { get; set; }
}

public class Artist
{
    public int Id { get; set; }
    public string Name { get; set; }
}

如果您允许 EF 基于此模型生成数据库,您会发现 Media 表将包含一个名为 Artist_Id 的列,它是对 Artist 表的外键引用。

如果您决定改为并行创建数据库(例如,手动),那么您需要设计数据库以正确利用 EntityFramework Conventions,或使用 Data AnnotationsEntityFramework Fluent Mappings..

此时我的建议 - 如果您真的希望进行代码优先开发 - 将创建类并使用 EF 到 generate the database

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多