强制HasMany()使用关联表

时间:2015-12-11 09:16:30

标签: c# entity-framework ef-migrations

这里的第一个问题,即使我多年来一直在浏览堆栈。

我有实体框架和迁移的问题,更准确地说是映射问题。 我很清楚所有关于多对多,一对多,关联表和东西的问题,但我没有找到解决这个特定问题的方法:

这些是我的POCO:

public class A
{
    public virtual long Id {get; set;}

    public virtual ICollection<B> B {get; set;}
}

public class B
{
    public virtual long Id {get; set;}

    // Not relevant stuff ...
}

我想强制映射给我一个关联表,可能看起来像这样:

-----------   -----------   -----------
| TABLE A |   | TABLE AB|   | TABLE B |
-----------   -----------   -----------
| ID      |   | FK_A_ID |   | ID      |
-----------   | FK_B_ID |   -----------
              -----------

我的第一反应是使用这种映射:

modelBuilder.Entity<A>()
                .HasMany(x => x.B)
                .WithMany()
                .Map(x =>
                {
                    x.ToTable("AB");
                    x.MapLeftKey("Id");
                    x.MapRightKey("Id");
                });

不幸的是,这并没有给我在数据库中所需的映射,因为它在表A中引用B.Id创建了一个外键。另外,我不想在B类中的A上拥有属性。有关信息,目标数据库是SqlServer。

有没有正确的方法呢?

注意:我不是母语为英语的人,如果我犯了错误,请原谅我。

1 个答案:

答案 0 :(得分:0)

不确定为什么要努力实现这一目标,但是,这是可能的。

我想到的是,您不能同时编辑ABA,但您想要许多关系......所以这是一个解决方案:

只需创建一个id为Bclass AB { virtual public A ALink {get; set;} [Key, Column(Order = 0)] public int ALinkId {get; set;} virtual public B BLink {get; set;} [Key, Column(Order = 1)] public it BLinkId {get; set;} } 的类 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <cxf:bus> <cxf:features> <cxf:logging/> </cxf:features> </cxf:bus> <jaxrs:server id="base" address="/rest"> <jaxrs:serviceBeans> <ref bean="MultiArgs" /> </jaxrs:serviceBeans> </jaxrs:server> <bean id="MultiArgs" class="com.multiArgs.MultiArgsImpl" /> </beans> ,然后使用装饰器定义键和识别器

<form class="form-horizontal" action="">
    <div class="form-group">
        <input type="text" name="key_word" class="form-control" value="">
        <button type="submit" class="btn btn-primary btn-bg-red">
            GO
        </button>
    </div>
</form>