如何实现可选关系?

时间:2016-01-22 19:26:55

标签: sql postgresql

我有一张表A和B,两者都是这样的:

[TestFixture]
public class StackQuestionTest
{
    [Test]
    public void GivenABsonDocumentWithANullForAnPossibleEmbeddedDocument_When_ThenAnInstanceIsSetAsTheEmbeddedDocument()
    {
        BsonSerializer.RegisterSerializationProvider(new VehicleEntryBsonSerializationProvider());

        var document = new BsonDocument()
        {
            {"OtherProperty1", BsonString.Create("12345")},
            {"OtherProperty2", BsonString.Create("67890")},
            {"VehicleEntry", BsonNull.Value},
        };

        var rootObject = BsonSerializer.Deserialize<RootObject>(document);

        Assert.That(rootObject.OtherProperty1, Is.EqualTo("12345"));
        Assert.That(rootObject.OtherProperty2, Is.EqualTo("67890"));
        Assert.That(rootObject.VehicleEntry, Is.Not.Null);
        Assert.That(rootObject.VehicleEntry.What, Is.EqualTo("Magic"));
    }
}

public class VehicleEntrySerializer : BsonClassMapSerializer<VehicleEntry>
{
    public override VehicleEntry Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        if (context.Reader.GetCurrentBsonType() == BsonType.Null)
        {
            context.Reader.ReadNull();

            return new VehicleEntry();
        }

        return base.Deserialize(context, args);
    }

    public VehicleEntrySerializer(BsonClassMap classMap) : base(classMap)
    {

    }
}

public class VehicleEntryBsonSerializationProvider : IBsonSerializationProvider
{
    public IBsonSerializer GetSerializer(Type type)
    {
        if (type == typeof(VehicleEntry))
        {
            BsonClassMap bsonClassMap = BsonClassMap.LookupClassMap(type);

            return new VehicleEntrySerializer(bsonClassMap);
        }

        return null;
    }
}


public class RootObject
{
    public string OtherProperty1 { get; set; }

    public string OtherProperty2 { get; set; }

    public VehicleEntry VehicleEntry { get; set; }
}

public class VehicleEntry
{
    public string What { get; set; } = "Magic";
}

现在我想建模一个A和B之间可选的一对多关系。通常,我会像这样扩展B的定义:

CREATE TABLE A (id integer CONSTRAINT aid PRIMARY KEY);

但现在CREATE TABLE B ( id integer CONSTRAINT bid PRIMARY KEY, a_id integer REFERENCES A(id) ); 不能是a_id,因此该关系不是可选的。所以基本上我希望能够将null分配给此列,但如果该值不为null,则它必须引用null

2 个答案:

答案 0 :(得分:1)

是的,表a_id中的B可以为空。我试过了:

tmp=# CREATE TABLE A (id integer CONSTRAINT aid PRIMARY KEY);
CREATE TABLE
tmp=# CREATE TABLE B (
tmp(#     id integer CONSTRAINT bid PRIMARY KEY, 
tmp(#     a_id integer REFERENCES A(id)
tmp(# );
CREATE TABLE
tmp=# insert into B (id,a_id) VALUES (3,null);
INSERT 0 1
tmp=#

您当前的数据模型有效。

答案 1 :(得分:-2)

你制作另一个与A和B相关的表,它只包含'可选'关系