这些是我的课程:
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public virtual ICommentInfo[] Comments { get; set; }
}
public class CommentInfo : ICommentInfo
{
public virtual string Author { get; set; }
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual int PostId{ get; set; }
[ForeignKey("PostId")]
public virtual Post Post { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
将此 CommentConfiguration …
foreign-key-relationship code-first navigation-properties ef-code-first entity-framework-5
实体框架核心中存在一个有趣的特征:
实体框架核心将自动将导航属性修复到先前加载到上下文实例中的任何其他实体.因此,即使您没有明确包含导航属性的数据,如果之前加载了部分或全部相关实体,仍可能会填充该属性.
在某些情况下这很好.然而,目前我正在尝试使用高级语法添加来建模多对多关系,并且不想检查,我创建的映射效果很好.
但我实际上不能这样做,因为如果让我说我有类似的东西:
class Model1{
... // define Id and all other stuff
public ICollection<Model2> Rel {get; set;}
}
Model1 m1 = new Model1(){Id=777};
m1.Rel.Add(new Model2());
ctx.Add(m1);
ctx.SaveChanges()
var loaded = ctx.Model1s.Single(m => m.Id == 777);
Run Code Online (Sandbox Code Playgroud)
因此,由于自动修复loaded.Rel
字段已经填充,即使我不包含任何内容.所以有了这个功能,我实际上无法检查任何内容.无法检查我是否使用了正确的映射,并且我的添加Include
工作正常.考虑到这一点,我应该更改哪些能够对我的导航属性进行正常测试?
我创建了一个应该通过的测试用例,但现在失败了.那里可以找到确切的代码
我正在使用.Net Core 2.0预览1和EF核心.
我有一个实体User
,它有两个属性CreatedBy
并且UpdatedBy
都引用User
. 默认情况下,EF 假定这两者是一对一的关系。我收到以下错误消息:
消息:System.InvalidOperationException:无法确定在“User.CreatedBy”和“User.UpdatedBy”之间检测到的一对一关系的子/从属端。要识别关系的子/依赖方,请配置外键属性。如果这些导航不应该是同一关系的一部分,请在不指定反向的情况下配置它们。有关更多详细信息,请参阅http://go.microsoft.com/fwlink/?LinkId=724062。
目前,我有一个这样的课程:
public class User
{
public int Id { get; set; }
public int? CreatedById { get; set; }
public User CreatedBy { get; set; }
public int? UpdatedById { get; set; }
public User UpdatedBy { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
基本上,这就是我正在尝试的:
CreatedBy
,任意数量的用户都可以拥有相同的UpdatedBy
。我怎样才能让 EF 忽略导航属性?我拥有的主要原因CreatedBy
是我Include(u => u.CreatedBy)
以后可以使用。我知道使用IEnumerable<User> AllCreatedUsers
属性可以解决这个问题,但我不想为IEnumerable
我的实体中的每个创建一个。有没有办法用流畅的 API …
c# navigation-properties entity-framework-core ef-fluent-api ef-core-2.0
我正在努力建立多对一的关系.表示"many"的实体具有指向父实体的导航属性.它看起来像这样:
public abstract class BaseEntity
{
/// <summary>
/// Key Field for all entities
/// </summary>
///
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
/// <summary>
/// Date entity was created
/// </summary>
public DateTime DateCreated { get; set; }
/// <summary>
/// Last date Modified
/// </summary>
public DateTime DateModified { get; set; }
/// <summary>
/// keep track of Row Version used for concurrency
/// </summary>
[Timestamp]
public Byte[] RowVersion { get; set; }
}
public …
Run Code Online (Sandbox Code Playgroud) c# entity-relationship navigation-properties ef-code-first entity-framework-4.1
与EntityFramwork(Code First)建模1-n关系的常用方法是使用虚拟集合属性,如:
class Project {
public virtual ICollection<Remark> Remarks { get; set; }
}
class Remark {
public virtual int ProjectId { get; set; }
public virtual Project Project {get; set; }
}
Run Code Online (Sandbox Code Playgroud)
由于Remarks
最初的收集null
,我采取以下方法
private ICollection<Remark> _remarks;
public virtual ICollection<Remark> {
get {
if (_remarks == null)
_remarks = new List<Remark>();
return _remark;
}
set {
_remarks = value;
}
}
Run Code Online (Sandbox Code Playgroud)
为了Remarks.Add
在新创建的Project
对象上使用该方法而无需明确设置Property.
Afaik EF内部派生自我的类并覆盖虚拟导航属性以支持延迟加载.
我的问题:我是否需要定义集合属性的setter?EF需要吗?我更愿意只暴露getter并让类在内部管理集合.
编辑 Accidentially我只是在postin mine之后才注意到这个相关的问题,所以也许它只是重复...
我正在使用Entity Framework(采用代码优先方法),并且使用预期的外键和唯一键约束成功创建了数据库。
我有这两个模型类:
public class Foo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Index(IsUnique = true), StringLength(512)]
public string Url { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
而这个应用程序代码:
var foo = GetData();
using (DatabaseContext db = new DatabaseContext())
{
db.Entry(foo).State = EntityState.Added;
if (foo.Bar != null)
{
var bar = await db.Bar.FirstOrDefaultAsync(x => x.Url == foo.Bar.Url);
if (bar …
Run Code Online (Sandbox Code Playgroud) c# entity-framework navigation-properties data-annotations ef-code-first
我正在修改我的应用程序,以便能够指定要在存储库中加载的导航属性。
模型:Team和TeamTunerUser可以在域实体中找到。
仓库:
namespace Sppd.TeamTuner.Infrastructure.DataAccess.EF.Repositories
{
internal class Repository<TEntity> : IRepository<TEntity>
where TEntity : BaseEntity
{
/// <summary>
/// Gets the entity set.
/// </summary>
protected DbSet<TEntity> Set => Context.Set<TEntity>();
/// <summary>
/// Gets the DB context.
/// </summary>
protected TeamTunerContext Context { get; }
public Repository(TeamTunerContext context)
{
Context = context;
}
public async Task<TEntity> GetAsync(Guid entityId, IEnumerable<string> includeProperties = null)
{
TEntity entity;
try
{
entity = await GetQueryableWithIncludes(includeProperties).SingleAsync(e => e.Id == entityId);
}
catch (InvalidOperationException) …
Run Code Online (Sandbox Code Playgroud) 我已经使用以下代码配置了我的 DbContext(EF Core 5.0):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(p => p.Roles)
.WithMany(p => p.Users)
.UsingEntity<Dictionary<string, object>>("UsersToRoles",
x => x.HasOne<Role>().WithMany().HasForeignKey("UserId"),
x => x.HasOne<User>().WithMany().HasForeignKey("UserId"),
x => x.ToTable("UsersToRoles"));
modelBuilder.Entity<Role>()
.ToTable("Roles")
.Property(r => r.Application)
.IsRequired();
base.OnModelCreating(modelBuilder);
}
Run Code Online (Sandbox Code Playgroud)
问题是我不希望Role
实体持有Users
. 我保留它是因为 EF Core 需要它来配置多对多关系。
有没有办法创建相同的关系,但不必定义Role.Users
导航属性?
.net c# many-to-many navigation-properties entity-framework-core
我有一个场景,我需要在一个列上订购,该列是我的EF模型中的Users实体的导航属性.
实体:用户 - >国家1:n关系
一个简单的SQL查询如下:
SELECT UserId, u.Name, c.Name
FROM users u join countries c on u.CountryId = c.CountryId
ORDER BY c.Name asc;
Run Code Online (Sandbox Code Playgroud)
所以我尝试使用Linq to Entities复制上面的SQL查询,如下所示 - (启用了延迟加载)
entities.users.OrderBy(field => field.country.Name).ToList();
Run Code Online (Sandbox Code Playgroud)
但是这个查询不会返回按照上面的本机SQL查询按名称排序的国家/地区.
但是我继续了一点,做了以下事情:
var enumeratedUsers = entities.users.AsEnumerable();
users = enumeratedUsers.OrderBy(fields => fields.country.Name).ToList();
Run Code Online (Sandbox Code Playgroud)
但是在enumeratedUser对象上排序约50条记录.7秒
有没有更好的方法来省略Enumerable并且不返回匿名类型?
谢谢
编辑
我只是忘了说EF提供者是MySQL而不是MS SQL.事实上,我只是在MS SQL中的复制数据库上尝试了相同的查询,并且查询工作正常,即国家名称正确排序,所以看起来除了从MySQL获取结果集并执行顺序之外别无选择来自可枚举对象的内存
在XAML中,DataGrid绑定到一个名为EF实体的列表Results
.一列被绑定到Count
的Buildings
导航属性.延迟加载已关闭.所以我需要包含Buildings
在查询中,以获得它的数量.这会导致性能问题,因为整个Buildings
实体集合会在内存中加载.但我只需要Count
它.有没有办法获得Count
导航属性而不将其加载到内存中?
var resQuery =
db.BAStreets
.Include("Street.StreetType")
.Include("Area.District")
.Include("Buildings")
.Where(x => true);
Results = resQuery.ToList();
Run Code Online (Sandbox Code Playgroud)
在XAML中绑定:
<DataGridTextColumn Binding="{Binding Buildings.Count}"/>
Run Code Online (Sandbox Code Playgroud)
还有一点其他问题.我用它:.Where(x => true)
将DbSet强制转换为IQueryable.看起来这是一种气味的东西.什么是标准模式?
c# xaml entity-framework eager-loading navigation-properties
c# ×7
.net ×2
asp.net-core ×1
code-first ×1
ef-core-2.0 ×1
many-to-many ×1
setter ×1
sql-order-by ×1
xaml ×1