gpt4 book ai didi

asp.net - 将附加属性添加到 Entity Framework 4编码第一个CTP 5实体

转载 作者:行者123 更新时间:2023-12-04 05:05:05 24 4
gpt4 key购买 nike

我正在使用ASP.NET MVC 3Entity Framework code first CTP 5。我想知道是否可以添加未映射到表列的其他属性?

我有一个News类,它的定义如下:

public class News : Entity
{
public int NewsId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public bool Active { get; set; }
}

我的数据库上下文类:
public class MyContext : DbContext
{
public DbSet<News> Newses { get; set; }
}

在实体类中,我有一个定义如下的属性:
public IList<RuleViolation> RuleViolations { get; set; }

我还没有编写这部分代码,但是我希望在验证对象时将所有坏规则添加到此列表中。我得到的错误是:
One or more validation errors were detected during model generation:

System.Data.Edm.EdmEntityType: : EntityType 'RuleViolation' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: The EntitySet RuleViolations is based on type RuleViolation that has no keys defined.

这是我的存储库代码:
public News FindById(int newsId)
{
return context.Database.SqlQuery<News>("News_FindById @NewsId",
new SqlParameter("NewsId", newsId)).FirstOrDefault();
}

更新2011-03-02:

这是我的 Entity类:
public class Entity
{
public IList<RuleViolation> RuleViolations { get; set; }

public bool Validate()
{
// Still needs to be coded
bool isValid = true;

return isValid;
}
}

这是我的 RuleViolation类:
public class RuleViolation
{
public RuleViolation(string parameterName, string errorMessage)
{
ParameterName = parameterName;
ErrorMessage = errorMessage;
}

public string ParameterName { get; set; }
public string ErrorMessage { get; set; }
}

这是我的上下文类:
public class MyContext : DbContext
{
public DbSet<News> Newses { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<News>().Ignore(n => n.RuleViolations);
}
}

最佳答案

您可以使用Fluent API忽略类型,方法是在OnModelCreating类的MyContext方法中添加忽略规则

public class MyContext : DbContext {

public DbSet<News> Newses { get; set; }

protected override void OnModelCreating(ModelBuilder builder) {

builder.Ignore<RuleViolation>()

}

}

或者,您可以使用 NotMapped属性忽略该属性
public class Enitity {

[NotMapped]
public IList<RuleViolation> RuleViolations { get; set; }

//other properties here

}

然后 Entity Framework 将忽略该属性。

关于asp.net - 将附加属性添加到 Entity Framework 4编码第一个CTP 5实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5155853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com