문제

I use Entity framework with Generate T-SQL Via T4 (TPH).xaml (VS) and SSDLToSQL10.tt (VS) templates. I have a table

TABLE [dbo].[Users](
    [UserId] [int] IDENTITY(1,1) NOT NULL,
    [UserName] [nvarchar](100) NOT NULL,
    [Password] [nvarchar](50) NOT NULL,
    [IsPaid] [bit] NOT NULL

Since I have 2 user types, field IsPaid is the discriminator. I created TPH in my model. Classes generated via .tt are

public abstract partial class User
    {
        public User()
        {
        }

        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

public partial class RegularUser : User
{
}

public partial class PaidUser : User
{
}

    public Container()
        : base("name=Container")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public DbSet<User> Users { get; set; }

Let's say I have Regular user with id 3. I create a new paid user u with the same data and try to save it.

using (var entities = new Container())
            {
                entities.Entry(u).State = u.UserId == 0 ? EntityState.Added : EntityState.Modified;
                entities.SaveChanges();
            }

Nothing happens. And I can see from the profiler that the query doesn't use IsPaid column at all. Can anyone help?

도움이 되었습니까?

해결책

Are you trying to change regular user with Id = 3 to paid user with Id = 3? That is not possible without executing direct SQL update. From perspective of EF the entity type is permanent. It is same like when you work with objects - you cannot "convert" regular user to paid user without creating whole new instance which will have different memory allocation (= different Id).

If your business logic expects that regular user can become paid user than EF inheritance is not a solution because it cannot do that. The only way to "change" regular user to paid user is creating whole new instance of paid user, inserting it to database and deleting old instance of regular user (sure you must also fix all relations from user to other entities).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top